I’m having trouble getting fields_for to work on an Array attribute of a non-ActiveRecord model.
Distilled down, I have to following:
models/parent.rb
class Parent
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
extend ActiveModel::Translation
attr_accessor :bars
end
controllers/parent_controller.rb
def new_parent
@parent = Parent.new
@parent.bars = ["hello", "world"]
render 'new_parent'
end
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
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).
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?
I think the correct technique is:
Quite why it can’t be made to Just Work I’m not sure, but this seems to do the trick.