如何使用 :selected with grouped_collection_select [英] How to use :selected with grouped_collection_select
问题描述
是否可以通过 grouped_collection_select 函数以某种方式使用您在普通选择视图助手上使用的 :selected 选项?我想设置在我的列表中预先选择的值.我试过传入 :selected 作为一个没有运气的选项!
Is it possible to somehow use the :selected option that you'd use on a normal select view helper with the grouped_collection_select function? I'd like to set the value that gets pre-selected in my list. I've tried passing in :selected as an option with no luck!
这是我测试的一些代码片段:
Here's some code snippts of my tests:
grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, { :include_blank => true, :selected => 5 }
grouped_collection_select 'user[subscription_attributes]', :subscription_plan_id, Trade.order(:name).all, :subscription_plans, :name, :id, :display_name, :include_blank => true, :selected => 5
两个版本都不行.未设置选择.我正在使用它来设置嵌套模型的值.我正在使用 railscasts 动态选择列表方法:http://railscasts.com/episodes/88-dynamic-select-menus-revised
Neither version works. No selected is set. I'm using this to set a value for a nested model. I'm using the railscasts dynamic select list methods: http://railscasts.com/episodes/88-dynamic-select-menus-revised
我无法让 formtastic 很好地与组选择一起玩,所以我不得不手动完成,但当用户验证失败时,我不会保持选中此值.我想在他们修复验证错误时保留这个设置.
I couldn't get formtastic to play nicely with the group selects so I had to do it by hand but I don't keep this value selected when a user fails validations. I'd like to keep this set when they fix validation errors.
推荐答案
我刚刚遇到了同样的问题,并使用 option_groups_from_collection_for_select helper
和 select
helper 文档解决了它在:http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html.
I just ran across the same problem and solved it using the option_groups_from_collection_for_select helper
and the select
helper documented at: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html.
第一步是创建分组选项.以您的示例为例,它应该如下所示:
The first step is to create the grouped options. Taking your example, it should look like:
<% options = option_groups_from_collection_for_select(Trade.order(:name).all,
:subscription_plans, :name, :id, :display_name, 5) %>
然后我创建了选择对象,如:
Then I created the select object like:
<%= select('user[subscription_attributes]', :subscription_plan_id, options,
include_blank: true) %>
你可以在一行中写出所有内容,我只是将选项分解到一个单独的变量中以说明两种不同的方法.
You could write it all out in one line, I just broke out the options into a separate variable to illustrate the two different methods.
这篇关于如何使用 :selected with grouped_collection_select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!