如何使用Squeel指定此查询?

siv*_*udh 1 arel ruby-on-rails-3.1 squeel

假设我有一个模型:

class Question < ActiveRecord::Base   
   attr_accessible :title  # it has title attribute   
   has_many :pictures 
end
Run Code Online (Sandbox Code Playgroud)

我想定义一个scope名为的查询completed:

返回以下所有问题:

  • 标题不是空的OR
  • 至少有1张照片

我怎样才能做到这一点?

到目前为止,我有:

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
Run Code Online (Sandbox Code Playgroud)

如果我能说:

class Question < ActiveRecord::Base   
   attr_accessible :title  # it has title attribute   
   has_many :pictures 

   scope :completed, where{title != "" || pictures.count > 0}
end
Run Code Online (Sandbox Code Playgroud)

Ger*_*rry 6

当然你可以用Squeel做到这一点!只需这样写你的范围:

scope :completed, joins{pictures.outer}.where{(title != "") | (pictures.id != nil)}.group{id}
Run Code Online (Sandbox Code Playgroud)

希望我帮忙.