0

我有一个带有 has_many 关联的模型:Charts has_many ChartConditions

图表模型具有以下字段:

  • 姓名(头衔)
  • 表名(型号)

chart_conditions 模型具有用于

  • assoc_name(到 .joins)
  • 名称(列)
  • 价值(价值)
  • 操作员(操作员

基本上,我的图表告诉我们要在哪个模型(使用 table_name 字段)上运行动态查询。然后 Chart 的 chart_conditions 将告诉我们要对该模型中的哪些字段进行排序。

所以在我要查询的模型中,我需要使用多个chart_conditions动态构建一个where子句。

下面你可以看到我首先根据所有对象的 assoc_name 字段进行连接

我想出的例子。这有效,但不适用于名称/值的动态运算符,并且还会引发弃用警告。

  def self.dynamic_query(object)
    s = joins(object.map{|o| o.assoc_name.to_sym})

    #WORKS BUT GIVES DEPRECATED WARNING (RAILS4)
    object.each do |cond|
      s = s.where(cond.assoc_name.pluralize.to_sym => {cond.name.to_sym => cond.value})
    end
  end

然后如何将我的动态运算符值添加到此查询中?还有为什么我不能说:

s = s.where(cond.assoc_name.pluralize : {cond.name : cond.value})

我必须使用 => 和 .to_sym 才能让它工作。上述语法错误:语法错误,意外':' ...ere(cond.assoc_name.pluralize : {cond.name : cond.value}) ... ^

4

1 回答 1

2

如果您将查询存储在变量中并附加到该变量中怎么办?

def self.dynamic_query(object)
  q = joins(object.map{|o| o.assoc_name.to_sym})
  object.each do |cond|
    q = q.where(cond.assoc_name.pluralize : {cond.name : cond.value})
  end
  q # returns the full query
end

另一种方法可能是merge(other)方法。从API 文档

如果 other 是 ActiveRecord::Relation,则合并来自 other 的条件。如果 other 是数组,则返回一个数组,该数组表示结果记录与 other 的交集。

Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
# Performs a single join query with both where conditions.

这可能有助于将所有条件结合在一起。

于 2013-09-10T14:13:44.450 回答