由于某种原因,当我提交表单 params[:user] 数组未发送 (POST):
app/views/groups/edit.html.erb
http://localhost:3000/groups/2
<%= form_for @group do |f| %>
<% @users.each_with_index do |u, n| %>
<%= fields_for "users[#{n}]", u do |ff| %>
<%= ff.select :city_id, grouped_options_for_select(City.states.map {|c| [c.state, City.by_state(c.state).map {|s| [s.name,s.id]}]}, u.city_id) %>
<% end %>
<% end %>
<%= f.submit 'Update Users' %>
<% end %>
输出
<form accept-charset="UTF-8" action="/groups/2" class="edit_group" id="edit_group_2" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="_method" type="hidden" value="put" /><input name="authenticity_token" type="hidden" value="iT3CGpXpQGxjjAGK9iv2I7x0cGr9d0pW6yc4svzTMFw=" /></div>
<select id="users_0_city_id" name="users[0][city_id]">
<optgroup label="State1">
<option value="1">City1</option>
<option value="2">City2</option>
</optgroup>
<optgroup label="State2">
<option value="3">City3</option>
<option value="4">City4</option>
</optgroup>
</select>
</form>
发送的参数
http://localhost:3000/groups/2/edit
Parameters: {"utf8"=>"✓", "authenticity_token"=>"iT3CGpXpQGxjjAGK9iv2I7x0cGr9d0pW6yc4svzTMFw=", "commit"=>"Update Users", "id"=>"2"}
任何帮助非常感谢
在您看来:
<%= form_for @group do |f| %>
<%= fields_for "users[#{n}]", u do |builder| %>
<%= builder.select :city_id, grouped_options_for_select(City.states.map {|c| [c.state, City.by_state(c.state).map {|s| [s.name,s.id]}]}, u.city_id) %>
<% end %>
<%= f.submit 'Update Users' %>
<% end %>
在组模型中:
has_many :users
accepts_nested_attributes_for :users
在控制器中,请确保构建用户,否则它们不会显示。
def new
@group = Group.new
users = User.all #obviously chose your own conditions
@group.users = users
end