1

假设我有一个模型:

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

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

返回满足以下条件的所有问题:

  • 标题不为空或
  • 至少有 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

如果我能说:

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

   scope :completed, where{title != "" || pictures.count > 0}
end
4

1 回答 1

6

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

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

希望我有所帮助。

于 2011-07-19T13:22:00.883 回答