Rails - 使用form_for和fields_for,如何在fields_for块中访问子对象? [英] Rails - Using form_for and fields_for, how do you access the sub-object while in the fields_for block?
问题描述
在我的第一个rails应用程序中,我试图使用 form_for
和 fields_for
来创建一个嵌套的对象窗体。到目前为止这么好,但我不知道如何在 fields_for
块中访问子对象。我已预填充子对象中的一个字段,其中包含要显示在用户说明中的数据。
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.
模型 >
Garage:
has_many :cars, :dependent => :destroy
accepts_nested_attributes_for :cars
Car:
belongs_to :garage
车库管理员
def new
@garage = Garage.new
for i in 1..5
@garage.cars.build :stall_number => i
end
end
_form.html.erb strong>
<%= 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 %>
正如您所看到的,在用于汽车的生成器块中,我想在我的用户中显示指令,字段: car.stall_number
(在我的控制器中填充一个整数):
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>
我尝试了许多不同的想法: @ car.stall_number
, object.car.stall_number
等。多次搜索并查看 fields_for
源代码并没有帮助我理解。我会很感激任何指导。
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.
更新:为了澄清,根据Dan的建议,我试过 builder.stall_number
但它会导致$< / p>
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>
推荐答案
我今天自己处理了这个问题。
I just dealt with this today myself.
您可以通过以下方式访问fields_for的对象:
You can access the object of the fields_for through:
builder.object
其中,构建器是您的fields_for表单构建器对象。在您的特定情况下,您可以说:
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>
这应该为你做!
这篇关于Rails - 使用form_for和fields_for,如何在fields_for块中访问子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!