【问题标题】:ActiveRecord chaining where with or relationActiveRecord 链接 where with or 关系
【发布时间】:2013-05-06 02:49:27
【问题描述】:

我在我的模型中链接了多个位置,看起来像这样 - user.watched_posts.commented_posts

whereWatched_posts 和 commented_posts 只是 User 模型中调用 where 的方法。 目前结果SQL在where条件之间有AND关系,
SELECT * FROM users WHERE (--watched_posts-) AND (--commented_posts--)

如何链接方法但获取和 OR 关系?
SELECT * FROM users WHERE (--watched_posts-) OR(--commented_posts--)

我不想创建像“watched_or_commented_posts”这样的方法,因为它会很奇怪...... 而且我还有很多其他方法会被链接起来,我需要 OR 关系。

您的帮助将不胜感激, 优西。

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord active-record-query


    【解决方案1】:

    ActiveRecord 接口不提供or 的包装器。然而,它是由 Arel 提供的,这也是 ActiveRecord 使用的。您可以使用 arel_table 类方法访问模型的 arel 表。

    看看 Arel github 的 OR 部分:

    https://github.com/rails/arel

    【讨论】:

    • 您的另一个选择是直接为 OR 提供 SQL。
    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2016-04-29
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多