Save 36% for Black Friday! Learn more

Tiago Teixeira

Joined

310 Experience
3 Lessons Completed
0 Questions Solved

Activity

Posted in Rails 6 autocomplete with add new

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.

logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.