Eki Eqbal
Eki Eqbal

Reputation: 6057

How to apply where clause in Rails ActiveRecord when the value is not nil?

Let's say I have User model and I want to apply some where clause only when the value is not nil and otherwise just discard the clause. Is there any better way than just use conditions like:

if ids.nil?
  User.where(active: true)
else 
  User.where(active: true, id: ids)
end

Is there more DRY way to do that?

Upvotes: 0

Views: 44

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

I normally use something along these lines:

search = { active: true }
search[:id] = ids if ids

User.where(search)

Upvotes: 1

Related Questions