简体   繁体   English

如何使用rails形式的文本从集合中选择对象

[英]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. 我想要一个文本输入来选择我的rails表单中的给定选项。

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. 我已经尝试过rails-jquery-autocomplete,并且我已经编写了一个ajax来将搜索结果插入到视图之前,但是在2019年它只是为了将选择框转换为文本输入而显得过于冗长和冗长。 If there is a best practice for filtering the given object collection in a rails form, I would like to know. 如果有一个以rails形式过滤给定对象集合的最佳实践,我想知道。 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 ) 我猜选择的js库可能是一个很好的选择,并且还有一个rails wrapper gem可用于此( https://github.com/tsechingho/chosen-rails

Include the gem in your gemfile and run bundle install 在gemfile中包含gem并运行bundle install

gem 'chosen-rails'

Include the following to application.js 在application.js中包含以下内容

//= require chosen-jquery

Include the following to application.scss 在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 并在java脚本中初始化如下

$('#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. 您可以在其官方页面( https://harvesthq.github.io/chosen/ )中参考各种选项库,并根据您的用例进行自定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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