Accepts_nested_attributes_for with belongs_to polymorphic attribute

I have 3 models and these associations for them

class User < ActiveRecord::Base
  # devise modules here
  attr_accessible :email, :password, :password_confirmation, :remember_me, :rolable_id, :rolable_type
  belongs_to :rolable, :polymorphic => true
end

class Player < ActiveRecord::Base
  attr_accessible :age, :name, :position
  has_one :user, :as => :rolable
end

class Manager < ActiveRecord::Base
  attr_accessible :age, :name
  has_one :user, :as => :rolable
end

I am out of the box from rails to put accepts_nested_attributes_for :rolablein a custom model, and in this accepts_nested_attributes_for with my own_to polymorphic argument I found some solutions for it, but the whole solution does not work for me. All solutions are always the same error when I try to create a user

    Processing by RegistrationsController#create as HTML
    Parameters: {"utf8"=>"V", "authenticity_token"=>"WKCniJza+PS5umMWCqvxFCZaRVQMPZBT4nU2fl994cU=", "user"=>{"email"=>"john@email.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "rolable_type"=>"manager", "rolable"=>{"name"=>"john", "age"=>"24"}}, "commit"=>"Sign up"}
    Completed 500 Internal Server Error in 143.0ms

    NoMethodError (undefined method `primary_key' for ActiveSupport::HashWithIndifferentAccess:Class):
    app/controllers/registrations_controller.rb:13:in `new'
    app/controllers/registrations_controller.rb:13:in `create'
+4
source share
2 answers

My mistake, I use a nested form

<%= f.fields_for :rolable do |rf| %>
 ....
<% end %>

change to

<%= f.fields_for :rolable_attributes do |rf| %>
 ....
<% end %>
+4
source

for association polymorphicyou must support a common model Roll, e.g.

class User < ActiveRecord::Base
  # devise modules here
  attr_accessible :email, :password, :password_confirmation, :remember_me
  has_many :rolls, :as => :rolable
end

class Player < ActiveRecord::Base
  attr_accessible :age, :name, :position
  has_many :rolls, :as => :rolable
end

class Manager < ActiveRecord::Base
  attr_accessible :age, :name
  has_many :rolls, :as => :rolable
end

class Roll < ActiveRecord::Base
  attr_accessible :rolable_id, :rolable_type
  belongs_to :rolable, :polymorphic=> true
end
0

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


All Articles