【问题标题】:building a dynamic where clause in model with ruby, iterating over activerecord object使用 ruby​​ 在模型中构建动态 where 子句,迭代 activerecord 对象
【发布时间】:2013-09-10 12:23:38
【问题描述】:

我有一个具有 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 才能让它工作。上述语法错误:syntax error, unexpected ':' ...ere(cond.assoc_name.pluralize : {cond.name : cond.value}) ... ^

【问题讨论】:

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


    【解决方案1】:

    如果将查询存储在变量中并附加到该变量中会怎样?

    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 Docs

    如果 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.
    

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

    【讨论】:

    • 如果我使用 scoped = scoped.where(cond.assoc_name.pluralize.to_sym => {cond.name.to_sym => cond.value}) 它可以工作,但是rails 控制台告诉我它已被弃用。如果我使用 scoped = scoped.where(cond.assoc_name.pluralize : {cond.name : cond.value}) 它会出错。此外,任何想法我将如何为名称做一个动态运算符:值,所以我可以使用我的表列中的动态运算符>
    猜你喜欢
    • 2011-08-14
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多