Rails 6 autocomplete with add new
In the past (back in rails 4) I used select2 or selectize to give me the ability to make a text field autocomplete as typed and have the option to create a new item, so basically tagging but only a single tag allowed. I recently got back into working on a project and upgrading to rails 6. Im new to stimulus and webpacker and wondering if there is a way to handle autocomplete with the option to create new for a field. Ive looked for some information already but couldnt find anything.
For context it has to do with a recipe database and for the ingredients of the recipes they have 3 fields (amount, unit, ingredient_id). Im wanting to have the ingredient_id field be a text field with autocomplete/add new that will reference my ingredient table so I can add data to the ingredients
Did you ever find a solution for this Alex? I'm very new to stimulus and I would love to know how to do autocomplete with it too :)
In case someone is still looking for a solution for this, I use Choice.js to do selects with search, it works as select2 or selectize but it's very small and does not require jQuery. It also allows to autocomplete text fields and has the option to add new values.
https://joshuajohnson.co.uk/Choices/
This is the controller I use to attach choices to a select element ( you can pass many options to new Choices
call):
import { Controller } from "stimulus"
const Choices = require('choices.js')
export default class extends Controller {
static targets = [ "input" ]
connect() {
this.inputTarget.choices = new Choices(this.inputTarget);
}
disconnect() {
this.inputTarget.choices.destroy();
}
}
In the view:
<div class="form-group" data-controller="select">
<%= form.label :relation_id %>
<%= form.select :relation_id, Relation.pluck(:name, :id), { include_blank: true }, class: "form-control", data: { target: "select.input" } %>
</div>
We initialise the controller outside the form.select
element because Choice.js will update the DOM replacing form.select
and this would cause the select controller to keep reloading on an infinite loop.