【问题标题】:Is it possible to generate SQL `OR` clauses by using scope methods?是否可以使用范围方法生成 SQL `OR` 子句?
【发布时间】:2012-07-12 00:22:00
【问题描述】:

我正在使用 Ruby on Rails 3.2.2 和 Squeel gem。我想知道是否有一种方法可以使用多个范围方法,以便使用与这些范围方法 SQL 条件相关的OR 子句生成 SQL 查询。也就是说,我有:

class Article < ActiveRecord::Base
  def self.scope_method_1
    ... # scope_method_1 SQL conditions
  end

  def self.scope_method_2
    ... # scope_method_2 SQL conditions
  end

  def self.scope_method_combination
    # I am looking for something like
    #
    # where{scope_method_1 | scope_method_2} # Note: The '|' means the SQL 'OR' clause in the Squeel context
    #
    # so to generate the following SQL query:
    #
    # SELECT FROM articles WHERE <scope_method_1 SQL conditions> OR <scope_method_2 SQL conditions>
  end
end

是否可以使用范围方法(通过使用或不使用 Squeel gem)生成 SQL OR 子句?

【问题讨论】:

  • 写一个带有OR sql语句的scope_method_3还不够吗?
  • @Trip - 我认为您正在考虑的 scope_method_3 无法遵循 DRY(不要重复自己)原则。

标签: sql ruby-on-rails ruby ruby-on-rails-3 squeel


【解决方案1】:

我们一直在squeel issue tracker 上讨论这个问题,基本答案似乎是否定的。至少没有范围;但是如果你把范围转换成筛子,你就可以。

【讨论】:

  • 我同意,我认为这与在进行联接时跟踪表名有关,范围只是没有提供足够的信息来保持代数的正确性......
猜你喜欢
  • 1970-01-01
  • 2023-02-24
  • 2022-01-23
  • 2023-01-19
  • 2018-09-25
  • 1970-01-01
  • 2021-04-29
  • 1970-01-01
  • 2011-07-26
相关资源
最近更新 更多