Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Forms Rails

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 .

like image 478
lesce Avatar asked Feb 22 '23 00:02

lesce


1 Answers

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 %>
like image 105
klump Avatar answered Feb 23 '23 15:02

klump