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
nested-forms ruby-on-rails-3 forms
Don Leatham Feb 18 2018-11-18T00: 00Z
source share