【发布时间】:2019-10-09 14:49:31
【问题描述】:
我正在寻找一种更好的方法来查询来自多态关联中使用的 2 个不同模型的用户。这是设置
class Schedule < ApplicationRecord
belongs_to :announcement
has_many :targets, dependent: :destroy
has_many :lists, through: :targets, source: :target, source_type: 'List'
has_many :accounts, through: :targets, source: :target, source_type: 'Account'
end
class Target < ApplicationRecord
# belongs_to :announcement
belongs_to :schedule
belongs_to :target, polymorphic: true
delegate :announcement, to: :schedule
end
class List < ApplicationRecord
belongs_to :account
has_many :targets, as: :target, dependent: :destroy
has_many :lists_users
has_many :users, through: :lists_users
end
class Account < ApplicationRecord
has_many :announcements, dependent: :destroy
has_many :targets, as: :target, dependent: :destroy
has_many :users, dependent: :destroy
end
目前我正在通过在 Schedule 模型中创建一个以这种方式获取用户的方法来解决这个问题:
def subscribers
targets.map(&:target).map(&:users).flatten.uniq
end
我查看了与 question 类似的东西,但似乎没有解决。
【问题讨论】:
-
多态关联中使用的第二个模型在哪里?
-
您希望
targets.map(&:target)集合包含不同类的实例还是只需要包含Account实例? -
正确,targets.map(&:target) 将是 Account 和 List 对象的集合,这两个对象都有用户。然后最终产品是基于 Account 中的用户和 List 中的用户的 User 对象的集合
-
您应该在
List中添加has_many :targets, as: :target以便理解 -
已编辑以显示具有 has_many 关联的列表。也许我没有正确理解这个概念或者我用错了,但如果我需要调用 Schedule.targets 并将该集合转换为他们各自的模型,这样我就可以抓住与他们关联的用户,为什么要我还需要列表中的 has_many 吗?如果您查看 Schedule 模型,您可以看到 Account 和 List 都被用作多态关联
标签: ruby-on-rails rails-activerecord has-many-through polymorphic-associations ruby-on-rails-6