Nested Forms Rails

我只是一个虾纸丫 提交于 2020-01-01 12:33:09

问题


I have 2 models User and Address .

class User < ActiveRecord::Base 
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
  belongs_to :user
end

My controller

  def new
    @user = User.new
    @user.addresses << Address.new
    @user.addresses << Address.new
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      #do something
    else
      render 'new'
    end
  end

And my View

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

My problem is I get only the last state,country,street entered in params .

"addresses_attributes"=>{"0"=>{"street"=>"test", "state"=>"test",, "country"=>"test"},
"1"=>{"street"=>"", "state"=>"", "country"=>""}} 

Also if there's a better way to do this I will appreciate any suggestions .


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9887154/nested-forms-rails

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