Nested Forms Rails

≡放荡痞女 提交于 2019-12-04 10:59:28

The rails API says that fields_for will be repeated by it self over each element in the collection of addresses.

I would suggest adding a kind of label to your addresses (like Work, Home, etc). And then it should work by itself. And with this label your are a bit more flexible when you want to add more addresses.

   <%= f.fields_for :addresses, @user.addresses do |a| %>
     <p> <%= a.object.label %> </p>
     <%= a.text_field :state %>
     <%= a.text_field :country%>
     <%= a.text_field :street %>
   <% end %>

fields_for :addresses already do the loop for you so you don't need to repeat state, country and street. So in your case, you can add new field address type then the controller should look like this:

def new
  @user = User.new
  @user.addresses.build(address_type: 'Home')
  @user.addresses.build(address_type: 'Work')
end

Then in the form:

<%= form_for @user do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>
    <%= f.fields_for :addresses do |a| %>
      <%= a.hidden_field :address_type %>
      <p><%= a.object.address_type %></p>
      <%= a.text_field :state %>
      <%= a.text_field :country%>
      <%= a.text_field :street %>
    <% end %>
  <% end %>
<% end %>

a.object refer to the address object.

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