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 the 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,有人有解决方案吗?
I have a fields_for tag, where I specify the prefix (lets say for some good reasons), and this is supposed to represent a one-to-one relationship.
I am trying to represent a relationship
widget has_many thingamagigs
thingamagig has_one whatchamacallit
The field_for code is:
fields_for "widgt[thingamagigs_attributes][][whatchamacallit_attributes]", thingamagig.whatchamacallit do |x|
which generates names (wrongly):
widget[thingamagigs_attributes][][whatchamacallit_attributes][][value]
The better solution would be
t.fields_for :whatchamacallit do |x|
where t = fields_for the thingamagig... However if I do that, the following names are generated
widgt[thingamagigs_attributes][whatchamacallit_attributes][]
which is completely wrong as all other fields for a thingamagig is...
widgt[thingamagigs_attributes][][name]
So in all cases I am screwed. The original field_for using a string cannot be used with accepts_nested_attributes_for :whatchamacallit
since whatchamacallit is a singular relationship and an object is expected not an array. The second fields_for will simply not work because rails cannot parse the params object correctly. Is there a way to tell the first forms_for to not add the [] after [whatchamacallit_attributes]
in all field names?
My current solution is to augment the model with
def whatchamacallit_attributes=(whatchamacallit_attributes)
assign_nested_attributes_for_one_to_one_association(:whatchamacallit, whatchamacallit_attributes[0])
end
Which will work even with the broken form fields. However this feels extremely hacky, does anyone have a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看来我必须坚持这个解决方案,因为没有提供其他任何东西。
Looks like I have to stick with this solution since nothing else was offered.