Nested Form Rails

I have 2 user models and an 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: 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 is a better way to do this, I will be grateful for any suggestions.

+4
source share
2 answers

The rails APIs says that fields_for will repeat itself for each element in the address collection.

I would suggest adding a shortcut to your addresses (e.g. Work, Home, etc.). And then he must work on his own. And with this shortcut you are a little more flexible if 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 %> 
+5
source

fields_for: Addresses already do the loop for you, so you don’t need to repeat the state, country and street. Therefore, in your case, you can add a new type of field address, 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 refers to an address object.

+3
source

Source: https://habr.com/ru/post/1403625/


All Articles