Search code examples
ruby-on-rails-3.1arelsqueel

How to specify this query using Squeel?


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

Solution

  • 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.