【问题标题】:ActiveRecord grab shared model from polymorphic associationActiveRecord 从多态关联中抓取共享模型
【发布时间】: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(&amp;: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


【解决方案1】:

我会这样做:

class Schedule < ApplicationRecord
  def subscribers
    # fetch all associated user IDs
    lists_user_ids = lists.joins(:lists_users).distinct.pluck("lists_users.user_id")
    accounts_user_ids = accounts.joins(:users).distinct.pluck("users.id")
    user_ids = (lists_user_ids + accounts_user_ids).uniq

    # fetch users by IDs
    User.where(id: user_ids)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多