【问题标题】:How to associate two joining models in ActiveRecord?如何在 ActiveRecord 中关联两个加入模型?
【发布时间】:2017-06-08 16:21:07
【问题描述】:

假设我们有 2 个 AR 模型:

class User < ApplicationRecord
  has_many :proposals
  has_many :concerns
end

class Job < ApplicationRecord
  has_many :proposals
  has_many :concerns
end

Proposal 和 Concern 都是 User 和 Job 之间的连接模型:

class Proposal < ApplicationRecord
  belongs_to :user
  belongs_to :job
end

class Concern < ApplicationRecord
  belongs_to :user
  belongs_to :job
end

我要解决的是如何通过用户和工作来关联提案和关注点。 IE。我想使用急切加载等:

proposals.preload(:concerns).map do |proposal|
  # proposal.concerns are preloaded here 
  # and all concerns have same user and job
end

我当前的解决方案只是简单的concerns 方法,它查找关注点 - 它无效,因为执行 N + 1 个查询。

我想避免向其中一个加入模型添加多余的外键。

【问题讨论】:

    标签: ruby-on-rails associations rails-activerecord


    【解决方案1】:

    这应该避免 N+1 个查询

    Proposal.includes(user: :concerns).where(condition: 123)
    

    【讨论】:

    • 不,这些关注点将包括与所有工作相关的所有用户关注点。
    • 那么您可以尝试在jobs上添加条件
    • 你到底想要什么
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多