Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

forms - Rails - Using form_for and fields_for, how do you access the sub-object while in the fields_for block?

In my first rails app I'm trying to use form_for and fields_for to create a nested object form. So far so good, but I can't figure out how to access the sub-object while in the fields_for block. I've pre-populated a field in the sub-object with 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 (populated in my controller with an integer):

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

I've tried a many different ideas: @car.stall_number, object.car.stall_number, etc. No joy. Multiple searches and a look at the fields_for source code haven't helped my understanding. I would appreciate any guidance.

Update: For clarification, per Dan's suggestion I have tried builder.stall_number but it results in a

NoMethodError: undefined method 'stall_number' for #<ActionView::Helpers::FormBuilder:0x00000102a1baf0>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I just dealt with this today myself.

You can access the object of the fields_for through:

builder.object

where builder is your fields_for form builder 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...