has_one:通过多态关联

时间:2013-08-13 16:00:50

标签: ruby-on-rails polymorphism has-many-through

我有这些模特和协会。我想达到角色的特权模型并不重要的是roleable_type(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)

1 个答案:

答案 0 :(得分:0)

我会制作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返回什么?