Reputation: 5472
I have a Rails query where I am selecting all trial ids where the names field is blank or nil. Is there a way to rewrite this so it's cleaner?
Trial.where(names: "").pluck(:id) + Trial.where(names: nil).pluck(:id)
Upvotes: 0
Views: 73
Reputation: 24367
The shortest way I know how to write it is:
Trial.where(name: [nil, '']).ids
This will find all Trial
record IDs where name
is NULL or blank. Tt produces the following SQL:
SELECT `trials`.`id` FROM `trials` WHERE ((`trials`.`name` = '' OR `trials`.`name` IS NULL))
Upvotes: 1
Reputation: 772
Trial.where("names = '' or names is null").pluck :id
Edit
There is a even cleaner option. Create a scope like this:
Trial Model:
class Trial < ActiveRecord::Base
scope :ids_with_blank_names, where("names = '' or names is null").pluck :id
end
Then in you controller you can use simply Trial.ids_with_blank_names
Upvotes: 0