Reputation: 6057
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
Reputation: 230561
I normally use something along these lines:
search = { active: true }
search[:id] = ids if ids
User.where(search)
Upvotes: 1