Aswin Mohan
Aswin Mohan

Reputation: 1022

How to Implement Autocomplete for Association in simple_form in Rails 6

I'm currently building a book handling project in Rails 6. There are two models Book and Categories, Category can contain many books but a book can only belong to a single category. I'm currently using simple_form f.association to make the form association which creates a dropdown menu of Categories.

new.html.erb in Book

    <section class="mt-8">
    <%= simple_form_for @book, defaults: { input_html: {class: 'form-input mt-1'}, wrapper_html: {class: 'flex flex-col my-2'}} do |f| %>
    <%= f.input :title %>
    <%= f.input :description, input_html: {class: 'form-textarea'} %>
    <%= f.input :amazon_url %>
    <%= f.association :category, collection: Category.all.order(name: :asc),input_html: {class: 'form-select'} %>
    <%= f.button :submit, 'Create New Book', class: 'mt-4 p-2 rounded-md bg-gray-400' %>
    <% end %>
</section>

I want the Categories list to be an autocomplete input. How do I implement this in Rails 6. I have tried various libraries but they all are outdated.

Upvotes: 1

Views: 1345

Answers (2)

Aswin Mohan
Aswin Mohan

Reputation: 1022

After a lot of digging I found the Choices library. It's entirely javascript based and due to the webpack asset compilation of Rails 6, works seamlessly.

I have written a blog post on the same. https://aswinmohan.me/posts/implementing-autocomplete-in-rails-6/

Upvotes: 2

catmal
catmal

Reputation: 1758

Chosen has support for Rails 6.

Upvotes: 1

Related Questions