I’m using the fields_for helper with accepts_nested_attributes_for
The System model has_many children.
If I do this in my haml template:
-form_for @system do |s|
=s.text_field :name
-s.fields_for :children do |child_fields|
=child_fields.text_field :name
all is fine. The fields_for iterates over all children and puts the
correct data in the fields.
But…what I want to do is access the child object in that loop.
With normal fields_for I could do:
=child_fields.object.foo()
within the loop, but that no longer works since child_fields.object is
nil.
How do I access the child object?
Do I just have to revert to creating a separate iteration over the
child objects?
Hi stuart.coyle
Assuming you have in model accepts_nested_attributes_for :children
In that case you can still access child record with
child_fields.object
Sijo
Ah! You’re right.
I was passing the child_fields object to a partial and that’s where it
was not working.
I’ve pulled the code out of the partial and it works fine.
Cheers.
Hi stuart.coyle
Ah! You’re right.
I was passing the child_fields object to a partial and that’s where it
was not working.
I’ve pulled the code out of the partial and it works fine.
Cheers.
Even in that case it will work.Do like
<%= render :partial => ‘partial_name’,:locals => {:f => child_fields}
And now in partial f.object
Sijo K George
I think I’m making life hard for myself.
Just browsed through the form_helper.rb code and found what was
happening.
def object
@object || @template_object.instance_variable_get("@#
{@object_name}")
rescue NameError
# As @object_name may contain the nested syntax (item
[subobject]) we
# need to fallback to nil.
nil
end
So when it’s a nested object I get nil.
InstanceTag goes through a bunch of acrobatics in initialize
to get the actual object values.
Still doesn’t give me any easy way to access the object of the
FormBuilder.