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

后端 未结 2 2058
梦毁少年i
梦毁少年i 2020-12-13 08:33

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 acc

2条回答
  •  有刺的猬
    2020-12-13 09:16

    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" %>
    <%= f.text_field :title %> <% for i in 1..5 %> <% f.fields_for @garage.cars[i] do |builder| %>

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

    <%= builder.label :license, "License #:" %>
    <%= 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).

提交回复
热议问题