Using form_for and fields_for, how do you access the sub-object in the fields_for field?

In my first rails application, I am trying to use form_for and fields_for to create a nested form of an object. So far so good, but I can’t figure out how to access the sub-object in the fields_for block. I prefilled the field in the sub-object with the data that I want to show in the user instructions.

Models
Garage:

 has_many :cars, :dependent => :destroy accepts_nested_attributes_for :cars 

Car:

 belongs_to :garage 

Garage controller

 def new @garage = Garage.new for i in 1..5 @garage.cars.build :stall_number => i end end 

_form.html.erb

 <%= form_for @garage do |f| %> <%= f.label :title, "Garage Name" %><br /> <%= f.text_field :title %> <% f.fields_for :cars do |builder| %> <p>Enter license for car parked in stall: <%= car.stall_number %></p> <%= f.label :license, "License #:" %><br /> <%= f.text_field :license %> <%= end %> <%= end %> 

As you can see, inside the builder block for: cars I want to show in my user instructions the field: car.stall_number (filled with an integer in my controller):

 <p>Enter license for car parked in stall: <%= car.stall_number%></p> 

I tried many different ideas: @car.stall_number , object.car.stall_number , etc. No joy. Repeated searches and looking at the source code of fields_for did not help me understand. I would be grateful for any recommendations.

Update:. For clarification, for Dan Dan's suggestion, I tried builder.stall_number , but this leads to

 NoMethodError: undefined method 'stall_number' for #<ActionView::Helpers::FormBuilder:0x00000102a1baf0> 
+44
nested-forms ruby-on-rails-3 forms
Feb 18 2018-11-18T00:
source share
2 answers

I just did it today.

You can access the fields_for through object:

 builder.object 

where builder is your fields_for form object. In your particular case, you can say:

 <p>Enter license for car parked in stall: <%= builder.object.stall_number%></p> 

That should do it for you!

+76
Mar 07 '11 at 20:26
source share

The way you try does not work because you want to access car without populating this variable for data.

I think you want to have several blocks of kiosks where you can enter license plates. For each stall, you will need your fields_for . I would suggest something like this:

 <%= form_for @garage do |f| %> <%= f.label :title, "Garage Name" %><br /> <%= f.text_field :title %> <% for i in 1..5 %> <% f.fields_for @garage.cars[i] do |builder| %> <p>Enter license for car parked in stall: <%= builder.stall_number%></p> <%= builder.label :license, "License #:" %><br /> <%= builder.text_field :license %> <% end %> <% end %> <% end %> 

In the fields_for field, you need to use the form object that you define there, in this case the builder. Since the data there is not displayed on the external form (f), but on the object (builder) of cars.

+3
Feb 18 2018-11-18T00:
source share



All Articles