2010-04-16 17 views
0

我有一個fields_for標記,在那裏我指定前綴(可以說有一些很好的理由),這應該表示一對一的關係。fields_for停止多元化

我想代表的關係

widget has_many thingamagigs 
thingamagig has_one whatchamacallit 

的field_for代碼:

fields_for "widgt[thingamagigs_attributes][][whatchamacallit_attributes]", thingamagig.whatchamacallit do |x| 

產生的名稱(錯誤地):

widget[thingamagigs_attributes][][whatchamacallit_attributes][][value] 

更好的解決辦法是

t.fields_for :whatchamacallit do |x| 

其中t = fields_for的thingamagig ......但是,如果我這樣做,下面的名稱產生

widgt[thingamagigs_attributes][whatchamacallit_attributes][] 

這是完全錯誤的,因爲所有其他領域的thingamagig是...

widgt[thingamagigs_attributes][][name] 

所以在所有情況下,我擰。由於whatchamacallit是單數關係,並且預期對象不是數組,所以使用字符串的原始字段不能用於accepts_nested_attributes_for :whatchamacallit。第二個fields_for將無法正常工作,因爲rails無法正確解析params對象。有沒有辦法告訴第一個forms_for在[whatchamacallit_attributes]之後的所有字段名稱中都不添加[]?

我目前的解決方案是

def whatchamacallit_attributes=(whatchamacallit_attributes) 
    assign_nested_attributes_for_one_to_one_association(:whatchamacallit, whatchamacallit_attributes[0]) 
end 

以增強模型將與破錶單域甚至工作。然而,這感覺非常黑客,有沒有人有解決方案?

回答

0
def whatchamacallit_attributes=(whatchamacallit_attributes) 
    assign_nested_attributes_for_one_to_one_association(:whatchamacallit, whatchamacallit_attributes[0]) 
end 

看起來像我必須堅持這個解決方案,因爲沒有其他提供。