【问题标题】:How to make where clause optional with ORM?如何使用 ORM 使 where 子句成为可选?
【发布时间】:2020-03-26 13:54:53
【问题描述】:

我有一个问题:

User.includes(:translations, :user_roles, :user_rating,
                              :user_verification, :portfolios, :reviews, :user_account,
                              :task_responses, :user_favorite_categories, :photo)
                    .where(
                      user_favorite_categories: { category: cat&.main_category_ids },
                      user_reviews: { review_type: 'author_as_contractor' }
                    )
                    .where('users.hidden_until is null OR users.hidden_until < ?', Time.current)

此查询包括用户的评论

如何使user_reviews: { review_type: 'author_as_contractor' } 子句可选?

选择没有评论的用户。

【问题讨论】:

  • 简单,只需删除它。摆脱 where 子句并将“user_reviews”添加到您的包含语句中,以便您以后可以根据需要有效地查询记录。

标签: sql ruby-on-rails ruby


【解决方案1】:

您可以像这样使用eager_loadwhere

User.eager_load(:reviews)
    .where(user_reviews: { review_type: ['author_as_contractor', nil] })

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 2020-07-30
    • 2021-05-20
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多