【问题标题】:Possible to add options to a chainable query?可以向可链接查询添加选项吗?
【发布时间】:2015-02-11 19:15:11
【问题描述】:

我正在将 Rails 3.2 应用程序升级到 Rails 4 方法,所以之前的程序员在纯 sql 语句中使用options 构建了一个查询,如下所示:

:conditions => 'a_table.an_attribute is NULL' + options

options 是附加的纯 sql 以进一步细化。

因此,当我将其转换为较新的方法时,我似乎无法让 options 像这样正常工作的语法正确:

self.joins(:tables1, :tables2).where(:something => :something_else).options

options 将使用 if 语句设置。

if true
   options = where(:attribute1 => :an_attribute)
else
   options = where(:attribute2 => :a_differant_attribute)
end

这是可行的还是我需要以不同的方法构建单独的完整查询?

谢谢。

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-4 ruby-on-rails-3.2


    【解决方案1】:

    您可以像这样以编程方式建立您的条件:

    scope = joins(:tables1, :tables2).where(:something => :something_else)
    
    if expression
      scope = scope.where(:attribute1 => :an_attribute)
    else
      scope = scope.where(:attribute2 => :a_differant_attribute)
    end
    

    【讨论】:

    • 我选择了scope :base_scope, -> {joins(:tables1, :tables2).where(:something => :something_else)},然后按照您的建议将其添加到 if 语句中。它工作正常。谢谢。
    猜你喜欢
    • 2021-09-26
    • 2016-04-19
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多