ActiveRecord :: AssociationTypeMismatch when trying to save nested attributes in Rails

I read many pages about the `has_one relationship and nested attributes, but was not successful in doing this. Any help would be fantastic.

Each user has a network. I try to collect information for both attributes in one form, but keep getting an ActiveRecord::AssociationTypeMismatch in UsersController#create exception

Past parameters:

 {"utf8"=>"รขล“"", "authenticity_token"=>"I54tm1ovzHEHaXbBLTT+5tqBJv2795sKg978ot3HDBc=", "user"=>{"name"=>"Bilbo Baggins", "email"=>" bilbo@lotr.com ", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "network"=>{"home_lng"=>"-87.91894912719727", "home_lat"=>"43.03812464542969", "center_lng"=>"-87.91894912719727", "center_lat"=>"43.03812464542969", "radius"=>"500"}}, "commit"=>"Sign up"} 

I assume that the parameters for Network should somehow display as network_attributes , but I'm not sure how to do this.

Controller:

 def create @user = User.new(params[:user]) if (@user.save) sign_in @user flash[:success] = "One ring to rule them all!" redirect_to @user else @title = "The journey begins..." render 'new' end end 

View:

 <%= f.label :name %> <%= f.text_field :name %> <%= f.label :email %> <%= f.text_field :email %><br /> <%= f.label :password %> <%= f.password_field :password %> <%= f.label :password_confirmation, "Confirmation" %> <%= f.password_field :password_confirmation %> <%= f.fields_for @network do |fn| %> <%= fn.hidden_field :home_lng %> <%= fn.hidden_field :home_lat %> <%= fn.hidden_field :center_lng %> <%= fn.hidden_field :center_lat %> <%= fn.hidden_field :radius %> <% end %> 

and, of course, Models:

 class User < ActiveRecord::Base attr_accessor :password attr_accessible :name, :email, :password, :password_confirmation, :network_attributes, :network has_one :network, :foreign_key => "user_id", :dependent => :destroy accepts_nested_attributes_for :network, :reject_if => :all_blank, :allow_destroy => true end class Network < ActiveRecord::Base attr_accessible :home_lng, :home_lat, :center_lng, :center_lat, :radius belongs_to :user end 

thanks

+4
source share
3 answers

If someone else has the same problem, I solved this by changing:

<%= f.fields_for @network do |fn| %> <%= f.fields_for @network do |fn| %> to <%= f.fields_for :network do |fn| %> <%= f.fields_for :network do |fn| %> and deletion :network as an available attribute from the user model.

+8
source

Not sure, think what you need:

 <%= f.fields_for @network, :network_attributes do |fn| %> 
+1
source

If you delete: the network from the model as available, it will not work for sure

0
source

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


All Articles