fields_for停止复数

时间:2010-04-16 05:38:59

标签: ruby-on-rails activeview

我有一个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]

所以在所有情况下我都搞砸了。使用字符串的原始field_for不能与accepts_nested_attributes_for :whatchamacallit一起使用,因为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

即使使用损坏的表单字段也可以使用。然而,这感觉非常hacky,有没有人有解决方案?

1 个答案:

答案 0 :(得分:0)

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

看起来我必须坚持使用此解决方案,因为没有提供其他任何内容。