【问题标题】:Rails query with has_many relation in a list of [types, ids]Rails 查询与 [types, ids] 列表中的 has_many 关系
【发布时间】:2019-11-29 09:02:56
【问题描述】:

我有带有变量的模型(许多模型类:多态关系),以及变量之间的约束(变量不一定在同一个模型中)。

我尝试进行查询以查找与模型列表关联的所有约束(以及与列表中的模型关联的所有变量),但我真的不知道该怎么做。

我的模型看起来像这样。

class Model1 < ApplicationRecord
  has_many :vars, as: :model
end
class Model2 < ApplicationRecord
  has_many :vars, as: :model
end

class Var < ApplicationRecord
  belongs_to :model, polymorphic: true
  # model_type and model_id in vars table
  has_many :cns_vars
  has_many :constraints, through: :cns_vars
end

class_CnsVar < ApplicationRecord
  belongs_to :var
  belongs_to :constraint
end

class Constraint < ApplicationRecord
  has_many :cns_vars
  has_many :vars, through: :cns_vars
end

要查找与一个模型相关的约束,我有以下查询:

Constraint.includes(:vars).where(active: true, vars: {model_id: model.id, model_type: model.class.to_s})

此查询为我提供了至少有一个与我的模型关联的 var 的约束。 我需要将所有变量与模型列表关联的约束。

有没有办法进行相同的查询,但所有变量都与模型相关联? 有没有办法进行相同的查询,但所有变量都与模型列表相关联?

Constraint.includes(:vars).where(active: true, vars: {*[var.model_type, var.model_id] in my models list*})

有没有一种解决方案可以用一个查询来做到这一点? 还是我必须以另一种方式来做?

感谢您的帮助。

(红宝石:2.6.0 / 导轨:5.2.3)

编辑: 为了给出更好的解释,看看这个返回我需要的函数,但这会产生太多的查询!

def constraints_for_models_list(models)
  all_vars = models.flat_map(&:vars)

  all_constraints = all_vars.flat_map(&:constraints)
  all_constraints.uniq!

  constraints = []
  all_constraints.each do |constraint|
    next unless constraint.vars.included_in?(all_vars)

    constraints << constraint
  end

  return constraints
end

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    Constraint.includes(:vars).where(active: true).where.not(vars: { model: nil }) 当然,如果我正确理解了您的尝试。

    对于您在评论中提出的问题: Constraint.includes(:vars).where(active: true).where('vars.model_type IN ?', ['Model1',Model2'])

    【讨论】:

    • 或者如果你想参数化范围:(model_types)-&gt; { includes(:vars).where(active: true, vars: { model: { type: model_types } })
    • 所有变量都与一个模型相关联(模型没有变量:nil)。我希望在一个特定的模型列表中带有模型的 vars。
    • 所以看看上面的评论
    • 我不搜索附加到特定模型类型的约束,而是搜索模型列表(此列表包括不同的模型类型)。
    • 我的模型列表不包括某些类型的所有模型... model_type 是多态关系的类名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多