Ruby-on-rails rails 选择带有多个预选值的标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2196382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails select tag with multiple values pre selected
提问by Omnipresent
I am trying to have a multiple select box. select box will contain all the stores in the DB but the ones that the user belongs to will be selected.
我想有一个多选框。选择框将包含数据库中的所有商店,但将选择用户所属的商店。
I'm half way there. I got a select box which has all the stores in the database. I'm unable to select the ones that the user belongs to.
我已经到了一半。我有一个选择框,其中包含数据库中的所有商店。我无法选择用户所属的那些。
I have the following:
我有以下几点:
<%= select_tag 'stores[]', options_for_select(@stores.map {|s| [s.store_name, s.store_id]},
:selected => @user.stores.map {|j| [j.store_name, j.store_id]}), :multiple => true, :size =>
10 %>
I have a map with stores that a user belongs to. it is in:
我有一张地图,上面有用户所属的商店。它在:
@user.stores
回答by Omnipresent
after a fair amount of trial and error the following worked for me:
经过大量的反复试验后,以下对我有用:
<%= select_tag 'stores[]', options_for_select(@stores.map { |s| [s.store_name, s.store_id] }, @user.stores.pluck(:id)), multiple: true, size: 10 %>
回答by Michael Yagudaev
Another way of doing this would be to use the options_from_collection_for_selecthelper method. It will look something like this:
另一种方法是使用options_from_collection_for_select辅助方法。它看起来像这样:
<%= select_tag 'stores[]', options_from_collection_for_select(@stores, :store_id, :store_name, [4,5,6]), multiple: true, size: '10%' %>

