form_for 非 AR 模型 - fields_for Array 属性不迭代 [英] form_for non-AR model - fields_for Array attribute doesn't iterate
问题描述
我无法让 fields_for
处理非 ActiveRecord 模型的 Array 属性.
I'm having trouble getting fields_for
to work on an Array attribute of a non-ActiveRecord model.
精炼下来,我必须遵循:
Distilled down, I have to following:
模型/parent.rb
models/parent.rb
class Parent
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Translation
attr_accessor :bars
end
控制器/parent_controller.rb
controllers/parent_controller.rb
def new_parent
@parent = Parent.new
@parent.bars = ["hello", "world"]
render 'new_parent'
end
views/new_parent.html.haml
views/new_parent.html.haml
= form_for @parent, :url => new_parent_path do |f|
= f.fields_for :bars, @parent.bars do |r|
= r.object.inspect
使用上面的代码,我的页面包含["hello", "world"]
——也就是在分配给<的Array上调用inspect
的结果代码>条形.(在 fields_for
行中省略了 @parent.bars
,我只显示 nil
).
With the code as above, my page contains ["hello", "world"]
- that is, the result of inspect
called on the Array assigned to bars
. (With @parent.bars
omitted from the fields_for
line, I just get nil
displayed).
如何使 fields_for
表现得像 AR 关联 - 也就是说,为我的 bars
数组的每个成员执行一次块中的代码?
How can I make fields_for
behave as for an AR association - that is, perform the code in the block once for each member of my bars
array?
推荐答案
我认为正确的技巧是:
= form_for @parent, :url => new_parent_path do |f|
- @parent.bars.each do |bar|
= f.fields_for "bars[]", bar do |r|
= r.object.inspect
为什么不能将其制作为 Just Work 我不确定,但这似乎可以解决问题.
Quite why it can't be made to Just Work I'm not sure, but this seems to do the trick.
这篇关于form_for 非 AR 模型 - fields_for Array 属性不迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!