![](/img/trans.png)
[英]ActiveRecord, has_many :through, and Polymorphic Associations
[英]Combining has_many :through with polymorphic associations
在Rails(5.2)应用程序中,我具有User
, Organization
, Subscription
和Event
。
User
属于Organization
, User
和Organization
可以订阅Event
。
现在,我需要一个User
通过其个人订阅和属于其组织的订阅来获取关联的事件。
我正在尝试创建可subscribable
多态关联。
subscriptions
表具有以下字段:
但是现在我陷入困境,不确定如何设置User
, Organization
和Subscription
之间的关联。
class User < ApplicationRecord
end
class Organization < ApplicationRecord
end
class Subscription < ApplicationRecord
belongs_to :subscribable, polymorphic: true
belongs_to :subscriber, polymorphic: true
end
该User
应同时为可subscribable
和subscriber
但我无法使其正常工作。
我应该如何在User
模型中设置关联?
下面的代码应该做
class Subscription < ApplicationRecord
belongs_to :subscribable, polymorphic: true
belongs_to :event
end
class User < ApplicationRecord
has_many :subscriptions, as: :subscribable
has_many :events, through: :subscriptions
belongs_to :organization
end
class Organization < ApplicationRecord
has_many :subscriptions, as: :subscribable
has_many :events, through: :subscriptions
has_many :users
end
现在,如果要呼叫用户的订阅和事件 ,则
@user.events
@user.subscriptions
如果要呼叫用户组织的 订阅和事件 ,则
@user.organization.events
@user.organization.subscriptions
用户应同时可订阅和订阅,但我无法使其正常工作。
不确定您的意思是什么,但是如果要获取订阅的订阅者,请在Subscription
模型中添加一个关联,如下所示
class Subscription < ApplicationRecord
belongs_to :subscribable, polymorphic: true
belongs_to :event
has_many :subscribers, source: :user
end
现在, @subscription.subscribers
将提供订阅该订阅的用户列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.