Skip to content
Advertisement

How to make where clause optional with ORM?

I’ve got a query:

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)

This query includes user’s reviews

How to make user_reviews: { review_type: 'author_as_contractor' } clause optional?

Select user even if he has no reviews.

Advertisement

Answer

You can use eager_load and where like this for that:

User.eager_load(:reviews)
    .where(user_reviews: { review_type: ['author_as_contractor', nil] })
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement