5

I have 3 models and this 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'm out of the box from rails way to put accepts_nested_attributes_for :rolable on user model and In this accepts_nested_attributes_for with belongs_to polymorphic question I found some solutions for it but all solution not works for me. All solutions, 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"=>"[email protected]", "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'

2 Answers 2

5

My mistake, I'm use nested form

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

change to

<%= f.fields_for :rolable_attributes do |rf| %>
 ....
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

Hey! Adding _attributes worked for me. Can tell why it worked?
0

for polymorphic association you have to maintain generic model Roll like

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

2 Comments

I hope this is what you want.. Polymorphic association
to be honest, my problem has long been the case, but I just remember it and try to reopen. I don't plan to add another model for my case, because I'm use my workflow apps Rails Devise Polymorphic - Get Render Partial Using Ajax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.