Rails'未初始化的常数'错误中的多态性

时间:2016-07-06 22:00:42

标签: ruby-on-rails ruby ruby-on-rails-4 model polymorphic-associations

我想在我的项目中建立多态关联,所以我跟着rails指南去做,但我得到了:minimal superkey 错误。

型号:

DashboardAssignment:

NameError: uninitialized constant DashboardAssignment::Assignable

用户:

class DashboardAssignment < ActiveRecord::Base
  belongs_to :dashboard
  belongs_to :assignable, polymorphic: true

  validates :dashboard, presence: true
  validates :assignable, presence: true, uniqueness: { :scope => :dashboard }
end

组:

class User < ActiveRecord::Base
  has_many :dashboard_assignments, as: :assignable
  has_many :dashboards, through: :dashboard_assignments
end

控制板:

class Group < ActiveRecord::Base
  has_one :dashboard_assignment, as: :assignable
  has_many :laboratories_assignments, as: :lab_assignable
end

在DashboardAssignment 迁移文件中,我有:

class Dashboard < ActiveRecord::Base
  has_one :building
  has_many :dashboard_assignments
  has_many :users, through: :dashboard_assignments, as: :assignable
end

当我尝试t.references :assignable, null: false, polymorphic: true, index: true DashboardAssignment.create(assignable: u)时创建新的DashboardAssignment 它给了我错误:

u = User.find(1)

我做错了吗?

我的rails版本 4.2.6

1 个答案:

答案 0 :(得分:1)

您应该在source关联中使用as而不是through

class Dashboard < ActiveRecord::Base
  has_one :building
  has_many :dashboard_assignments
  has_many :users, through: :dashboard_assignments, source: :assignable
end

我会提醒您,这可能会为您assignables提供类Group。解决此问题的最佳方法是为has_many的{​​{1}}添加一个条件,让您仅对dashboard_assignments dashboard_assignments的{​​{1}}进行过滤:

assignable_type = 'User'