1

モデルがあるとします:

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

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

私はちょうど言うことができればいいだろう:

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 に答える