如何使用 rails 中的当前 ID 预填充我的选择框
How do I pre-populate my selectbox with current ID in rails
我的表单中有一个 select 框,我可以从列表中选择一个用户。这可以正确保存并将用户应用于我的 Chasing 模型,但我想知道是否可以让 select 显示当前分配的用户,而不是每次编辑对象时都将其重置。我的表单代码是:
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}), { :include_blank => "Please select user"}, {:class => "form-control"} %>
我也这样做了,所以表单需要用户在场才能保存,但有时我需要保存一个新的带有默认用户的 Chasing(称为 'Unassigned')。有没有办法将 select 框默认给该用户 除非 Chasing 已经分配了一个用户?
如有任何帮助,我们将不胜感激:)
据此:http://apidock.com/rails/v4.2.1/ActionView/Helpers/FormOptionsHelper/options_for_select
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}, current_user.id), { :include_blank => "Please select user"}, {:class => "form-control"} %>
(将 current_user
替换为您要放置的用户对象)
只需在 collection
之后的 options_for_select
中添加 @object.field_name
,如下所示。
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}, @object.user_id), { :include_blank => "Please select user"}, {:class => "form-control"} %>
希望这能解决您的问题。
您可以将 :selected => value
作为参数传递
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}), { :include_blank => "Please select user"}, {:class => "form-control", :selected => o.customer_id } %>
我的表单中有一个 select 框,我可以从列表中选择一个用户。这可以正确保存并将用户应用于我的 Chasing 模型,但我想知道是否可以让 select 显示当前分配的用户,而不是每次编辑对象时都将其重置。我的表单代码是:
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}), { :include_blank => "Please select user"}, {:class => "form-control"} %>
我也这样做了,所以表单需要用户在场才能保存,但有时我需要保存一个新的带有默认用户的 Chasing(称为 'Unassigned')。有没有办法将 select 框默认给该用户 除非 Chasing 已经分配了一个用户?
如有任何帮助,我们将不胜感激:)
据此:http://apidock.com/rails/v4.2.1/ActionView/Helpers/FormOptionsHelper/options_for_select
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}, current_user.id), { :include_blank => "Please select user"}, {:class => "form-control"} %>
(将 current_user
替换为您要放置的用户对象)
只需在 collection
之后的 options_for_select
中添加 @object.field_name
,如下所示。
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}, @object.user_id), { :include_blank => "Please select user"}, {:class => "form-control"} %>
希望这能解决您的问题。
您可以将 :selected => value
作为参数传递
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}), { :include_blank => "Please select user"}, {:class => "form-control", :selected => o.customer_id } %>