fields_for 用于使用数组的 has_many 关联 [英] fields_for for has_many association using an array
问题描述
控制器: project_sub_types_controller.rb
def new
@svn_repos = ['svn_software','svn_hardware']
@project_sub_type = ProjectSubType.new
@project_sub_type.repositories.build
end
模型:project_sub_type.rb
class ProjectSubType < ActiveRecord::Base
belongs_to :project_type
has_many :repositories, :dependent => :destroy
accepts_nested_attributes_for :repositories
def repositories_attributes=(attributes)
# Process the attributes hash
end
end
查看:_form.html.erb
<%= form_for @project_sub_type, :html => {:class => 'project_subtype_form'} do |f| %>
<%= f.label :name, "Project sub type name" %>
<%= f.text_field :name %>
<%= f.fields_for :repositories do |ff| %>
<%= ff.label :select_svn_repositories, "Select SVN repositories" %>
<% @svn_repos.each do |repos| %>
<%= ff.check_box :repos_name, {}, "#{repos}", nil %>
<%= h repos -%>
<% end %>
<%= f.submit "Save"%>
fields_form 检查元素:
<input id="project_sub_type_repositories_attributes_0_repos_name" type="checkbox" value="svn_software" name="project_sub_type[repositories_attributes][0][repos_name]">
svn_software
<input id="project_sub_type_repositories_attributes_0_repos_name" type="checkbox" value="svn_hardware" name="project_sub_type[repositories_attributes][0][repos_name]">
svn_hardware
提交表单后 params = "repositories_attributes"=>{"0"=>{"repos_name"=>"svn_hardware"}}}
即使选中了两个复选框正在使用最后选择的复选框,即svn_hardware"
After submitting the form the params = "repositories_attributes"=>{"0"=>{"repos_name"=>"svn_hardware"}}}
even after checking both the checkboxes it is using the last selected check_box that is 'svn_hardware'
所需的输出:我的最终输出应该是用户选择的,所以在这种情况下,它应该是我提交后的参数 = "repositories_attributes"=>{"0"=>{"repos_name"=>"svn_software"}{"1"=>{"repos_name"=>"svn_hardware"}}
Desired Output : My final output should be what the user selects so in this case it should be like this in my after submit params = "repositories_attributes"=>{"0"=>{"repos_name"=>"svn_software"}{"1"=>{"repos_name"=>"svn_hardware"}}
推荐答案
正如 Nicolay 所解释的,你有 0 的原因是因为你构建了这个 @project_sub_type.repositories.build
对象一次.您代码中的所有内容都是正确的.但是,如果您必须选择多个复选框,则根据 DOCS
As Nicolay explains, the reason you have a 0 is because you build this @project_sub_type.repositories.build
object once. Everything in your code is correct. But if you have to select multiple checkboxes then according to the DOCS
在视图中:_form.html.erb改变
<%= ff.check_box :repos_name, {}, "#{repos}", nil %>
至
<%= ff.check_box :repos_name, {:multiple => true}, "#{repos}", nil %>
现在您应该可以在提交后看到params
,如下所示:
Now you should be able to see the params
after submit as below:
=>{"0"=>{"repos_name"=>["svn_software", "svn_hardware"]}}
=>{"0"=>{"repos_name"=>["svn_software", "svn_hardware"]}}
这篇关于fields_for 用于使用数组的 has_many 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!