1

我有这些模型和关联。我想达到可角色化的低谷特权模型,不管角色类型是什么(Dj 或摄影师)?使用连接模型,因为特权模型将具有其他属性。可能是这样的:

class User
  has_one :privilege, dependent: :destroy
  has_one :roleable, through: :privilege
end

class Dj < ActiveRecord::Base
  has_one :privilege
  has_one :user, through: :privilege, as: :roleable
end

class Photographer < ActiveRecord::Base
  has_one :privilege
  has_one :user, through: :privilege, as: :roleable
end

class Privilege < ActiveRecord::Base
  belongs_to :user
  belongs_to :roleable, polymorphic: true
end

如果我将 source_type: 'Dj' 添加到 has_many :通过仅使用 roleable_type 'Dj' 返回。我想在下面这样做:

u = User.first
u.roleable #return privilage roleable( doesnt matter Dj or Photograher)
4

1 回答 1

-1

我会做那些belongs_to,而不是改变任何东西。

class User < ActiveRecord::Base
  has_one :privilege, dependent: :destroy
  has_one :roleable, through: :privilege
end

class Dj < ActiveRecord::Base
  has_one :privilege
  belongs_to :user, through: :privilege, as: :roleable
end

class Photographer < ActiveRecord::Base
  has_one :privilege
  belongs_to :user, through: :privilege, as: :roleable
end

class Privilege < ActiveRecord::Base
  belongs_to :user
  belongs_to :roleable, polymorphic: true
end

可以发帖吗,u.roleable返回什么?

于 2013-08-13T16:27:37.877 回答