2017-02-20 72 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}}