Ruby on rails has_一:通过多态关联
我有这些模型和关联。我想通过特权模式接触roleable?无论roleable_类型是什么(Dj还是摄影师)?使用联接模型,因为特权模型将具有其他属性。可能是这样的:Ruby on rails has_一:通过多态关联,ruby-on-rails,polymorphism,has-many-through,Ruby On Rails,Polymorphism,Has Many Through,我有这些模型和关联。我想通过特权模式接触roleable?无论roleable_类型是什么(Dj还是摄影师)?使用联接模型,因为特权模型将具有其他属性。可能是这样的: class User has_one :privilege, dependent: :destroy has_one :roleable, through: :privilege end class Dj < ActiveRecord::Base has_one :privilege has_one :us
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
我会让那些
属于,这不会改变任何东西
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
class用户
您可以发布u.rolable
返回的内容吗?如果要创建联接表,您还需要一个rolable类。你写了吗?我想roleable成为Dj或摄影模特啊,好吧,听起来你应该做继承类。因此,与其让摄影师和DJ从ActiveRecord::Base继承,不如让他们从一个名为Roleable的类继承<代码>职业摄影师
。然后您仍然需要创建一个rolable.rb
文件。你也可以把你所有的共享方法都放在这里。如果这是你想要的,你就不需要摄影师或DJ的桌子了。只是一个表示Roleable的表。我需要dj和摄影师表,因为它们包含不同的方法和属性OK,所以u.Roleable
可能会返回Photgrapher对象?现在它返回了什么?hm属于不支持:通过将拥有什么:特权;属于:某物,通过::特权
mean?这是。。。不是循环关系就是荒谬的关系
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