Reputation: 32635
Suppose I have a model:
class Question < ActiveRecord::Base
attr_accessible :title # it has title attribute
has_many :pictures
end
I want to define a scope
query called completed
that:
Returns all questions whose:
- title is not empty OR
- has at least 1 picture
How can I do that?
So far, I have:
class Question < ActiveRecord::Base
attr_accessible :title # it has title attribute
has_many :pictures
scope :completed, where{title != ""} # returns all questions with non-empty title
end
It'd be nice if I could just say:
class Question < ActiveRecord::Base
attr_accessible :title # it has title attribute
has_many :pictures
scope :completed, where{title != "" || pictures.count > 0}
end
Upvotes: 1
Views: 2354
Reputation: 5336
Of course you can do this with Squeel! Just write your scope this way:
scope :completed, joins{pictures.outer}.where{(title != "") | (pictures.id != nil)}.group{id}
Hope I helped.
Upvotes: 6