accepted_toted_attributes_for with belongs_to polymorphic devise

时间:2014-06-18 05:30:20

标签: ruby-on-rails devise ruby-on-rails-3.2

我有3个模型和它们的关联

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

我从rails方式开箱即可将accepts_nested_attributes_for :rolable放在用户模型上。在这个accepts_nested_attributes_for with belongs_to polymorphic问题中我找到了一些解决方案,但所有解决方案对我都不起作用。所有解决方案,当我尝试创建用户时总是出现相同的错误

    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'

2 个答案:

答案 0 :(得分:5)

我的错误,我使用的是嵌套表格

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

更改为

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

答案 1 :(得分:0)

对于polymorphic关联,您必须维护通用模型Roll,如

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
相关问题