So I have the three models client, address and address_info. When I create a nested form for address and address_info however I get basically double the rows that I meant to give it. The first three rows will have the addresstype and clientid tied to it and the other three will have clientid and addressid tied to it. Here is an example of the output:
As you can see, the rows do not have both the address and the client id's associated with the row. I'm not sure how to fix that.
Here are my models:
#client model
has_many :address_infos
has_many :addresses, through: :address_infos
accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true
#addressinfo model
belongs_to :client
belongs_to :address
#address model
has_many :address_infos
has_many :clients, through: :address_infos
Here is my clients controller:
def new
@client = Client.new
@client.address_infos.build
@client.addresses.build
end
def create
@client = Client.new(client_params)
end
private
def client_params
params.require(:client).permit(:firstname, :middlename, :lastname,
addresses_attributes: [:street, :city, :state, :zipcode],
address_infos_attributes: [:ownorrent, :addresstype, :yearsofresidency])
end
end
Here is my view, note that there are also nested forms for a mailing and former address that I did not include:
<%= form_for(@client) do |f| %>
<%= f.fields_for :addresses do |addresses_form| %>
<!-- misc. code -->
<%= f.fields_for :address_infos do |addressinfo_form| %>
<%= addressinfo_form.label :ownorrent, "Own", :value => "Own" %>
<%= addressinfo_form.radio_button :ownorrent, :own %>
<%= addressinfo_form.label :ownorrent, "Rent", :value => "Rent" %>
<%= addressinfo_form.radio_button :ownorrent, :rent %>
<%= addressinfo_form.text_field :yearsofresidency, class:"form-control", id:"inputfield", placeholder:"Years" %>
<%= addressinfo_form.text_field :addresstype,:value => "presentaddress" %>
<% end %>
<% end %>
UPDATE So after doing what was suggested, I end up with this in my database: The address I tried to add was for 123 Fake St. The other things were seeded directly. The address_id still does not stick with the rest of the stuff. I also updated my current models.
You should control nested attributes before saving in DB. Use reject_if
or allow_blank
options to prevent and destroy blank records.
accepts_nested_attributes_for :addresses, :address_infos, reject_if: :all_blank, allow_destroy: true
For more options to control the params, visits the link http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
Thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.