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"=>"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'
Community
  • 1
  • 1
itx
  • 1,327
  • 1
  • 15
  • 38

2 Answers2

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 %>
itx
  • 1,327
  • 1
  • 15
  • 38
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
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
  • I hope this is what you want.. Polymorphic association – Gagan Gami Jun 18 '14 at 05:38
  • 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](http://stackoverflow.com/q/19446624/2858044) – itx Jun 18 '14 at 06:04