简体   繁体   中英

how to select a object from a collection using text in rails form

I want a text input to select the given options in my rails form.

f.collection_select(:user_id, User.all, :id, :name)

is the closest to what I want, but there are too many users to show as a dropdown.

I've tried rails-jquery-autocomplete, and I've written ajax to insert search results to the view before, but it all seems too much and verbose in 2019 just to convert a select box to a text input. If there is a best practice for filtering the given object collection in a rails form, I would like to know. Thank you.

I guess chosen js library might be a good option to consider and there is also a rails wrapper gem available for this ( https://github.com/tsechingho/chosen-rails )

Include the gem in your gemfile and run bundle install

gem 'chosen-rails'

Include the following to application.js

//= require chosen-jquery

Include the following to application.scss

*= require chosen 

Example usage:

Once the setup is complete you can use it as follows

<%= select_tag :users, options_for_select(User.all),class:"form- 
control",multiple:true id:chosen-select" %>

And initialise it in java script as follows

$('#chosen-select').chosen();

You can refer to various options library provides in their official page ( https://harvesthq.github.io/chosen/ ) and customise it to your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM