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

做~自己de王妃 提交于 2019-11-28 17:46:20

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!

Dan

The way you are trying is does not work because you want to access car without filling that variable for data.

I guess you want to have multiple blocks of stalls, where you can enter license plates. For each stall you will need your own fields_for. I would suggest something like that:

<%= 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 %>

Within the fields_for you need to use the form object you define there, in this case builder. Since the data there are not mapped to the outer form (f), but to the cars object (builder).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!