【问题标题】:SQL OR in scopes in Rails 3 / ArelRails 3 / Arel 范围内的 SQL OR
【发布时间】:2011-03-16 02:29:40
【问题描述】:

我正在尝试创建一个 Rails 3 模型范围,本质上是:

scope :published, where(:published => true)

scope :viewable_by, lambda { |user| where(:user_id => user.id).or(published) }

问题是,我找不到方法来完成这项工作。

我曾希望 arel_table 能工作,但它抱怨“无法访问 ActiveRecord::Relation”:

where(arel_table[:user_id].eq(user.id)).or(published)

这可以通过将“已发布”范围复制为 Arel 来完成,但随后我将重复代码(在我的项目中,“已发布”范围更深入一些)。

我能想到的最好的是:

scope :viewable_by, lambda { |user| where("(user_id = ?) OR (#{published.where_values.collect(&:to_sql).join(" AND ")})", user.id) }

【问题讨论】:

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


    【解决方案1】:

    这是我经过一番挖掘后能想到的最短的:

    scope :published, where(:published => true)
    scope :viewable_by, lambda { |user| where("user_id = ? OR #{published.where_clauses.first}", user.id) }
    

    (当然它只适用于单个 where 子句;如果有多个子句,请使用 join。)

    我建议使用像 MetaWhere 这样的 gem,它可以更清楚地展示 Arel 的一些基础。这是上面链接的主页中创建 OR 查询的示例:

    Article.where(:title.matches % 'Hello%' | :title.matches % 'Goodbye%').to_sql
     => SELECT "articles".* FROM "articles" WHERE (("articles"."title" LIKE 'Hello%'
        OR "articles"."title" LIKE 'Goodbye%'))
    

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2011-08-14
      • 2013-10-20
      • 2011-06-30
      • 1970-01-01
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      相关资源
      最近更新 更多