2017-02-20 73 views
0

所以我有这种关联关系:Rails。 HAS_MANY:通过和的form_for PARAMS一个复选框字段

class FirstModel 
has_many :merged_models 
has_many :second_models, :through => :merged_models 
end 

class SecondModel 
has_many :merged_models 
has_many :first_models, :through => :merged_models 
end 

class MergedModel 
belongs_to :first_model 
belongs_to :second_model 
end 

现在我的问题是要了解这一招,帮助帮助识别元素在HTML从传递的集合在我形式:

form_for(first_model) do |f| 

    <% SecondModel.all.each do |s| -%> 
    <div> 
     <%= check_box_tag 'second_model_ids[]', s.id, first_model.second_models.include?(s), :name => 'first_model[second_model_ids][]'-%> 
     <%= label_tag :second_model_ids, s.first_name -%> 
    </div> 
    <% end -%> 

我不明白的是:

first_model.second_models.include?(s), :name => 'first_model[second_model_ids][]' 

我相信这一点:

first_model.second_models.include?(s) 

检查SecondModel的对象ID已在FirstModel的second_model_ids阵列。在这种情况下,我希望类似的if语句 - 如果此ID是有那么做,等

这部分让我更糊涂了:

:name => 'first_model[second_model_ids][]' 

如果这一:name是从哪里来的?为什么first_model[second_model_ids][]有两个方括号 - 它们在Rails的语法是如何工作的?要合并这个新检查的ID给second_model_ids阵列?

,我将感谢所有信息。谢谢!

回答

1

所以check_box_tag具有这个签名:

check_box_tag(name, value = "1", checked = false, options = {}) 

在你的情况:

check_box_tag 'second_model_ids[]', s.id, first_model.second_models.include?(s), :name => 'first_model[second_model_ids][]' 

第一个参数(名称)是 'second_model_ids []',这将被用来作为id =部的标签。 复选框的第二个参数(值)为s的id(SecondModel的当前实例)。 第三个参数(选中):

first_model.second_models.include?(s) 

你是对的大概意思,你不需要一个“如果”。 include?()返回一个布尔值(就像大多数Ruby方法以问号结束一样)。你可以在IRB或导轨控制台试试这个:

[1,2,3].include?(2) 
# => true 

最后一个选项:

:name => 'first_model[second_model_ids][]' 

通行证在hash选项将被用来作为HTML。在这种情况下,使用key:name(不要与上面的第一个参数相混淆,它在html标签中用作id ='...')的单个哈希值,这将直接在标签中用作

name='first_model[second_model_ids][]' 

你对这里的语法也是正确的。括号帮助Rails的解析为params哈希表的正确嵌套这与

first_model: {foo: 1, bar: 2, second_model: {some: stuff, other: stuff}}