すべてのアクティブレコードモデルに検索条件を追加する方法はありますか?
つまり、このクエリが欲しいです
ExampleModel.find :all, :conditions=> ["status = ?", "active"]
と同じように動作します
ExampleModel.find :all
すべてのモデルで
ありがとう!!
すべてのアクティブレコードモデルに検索条件を追加する方法はありますか?
つまり、このクエリが欲しいです
ExampleModel.find :all, :conditions=> ["status = ?", "active"]
と同じように動作します
ExampleModel.find :all
すべてのモデルで
ありがとう!!
使用できますdefault_scope
:
class ExampleModel < ActiveRecord::Base
default_scope :conditions => ["status = ?", "active"]
end
これをすべてのモデルで使用したい場合は、すべてのモデルでサブクラス化ActiveRecord::Base
し、そこから派生させることができます (おそらく、単一テーブルの継承ではうまく機能しません)。
class MyModel < ActiveRecord::Base
default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < MyModel
end
...または、default_scope
onActiveRecord::Base
自体を設定することもできます (1 つのモデルがこのデフォルト スコープを持つべきではないと判断した場合、煩わしいかもしれません):
class ActiveRecord::Base
default_scope :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end
コメントで klochner が述べたように、たとえば、namedに anamed_scope
を追加することを検討することもできます。ActiveRecord::Base
active
class ActiveRecord::Base
named_scope :active, :conditions => ["status = ?", "active"]
end
class ExampleModel < ActiveRecord::Base
end
ExampleModel.active # Return all active items.
更新: Rails 3.1 でnamed_scope
廃止/名前変更されました。3.2.8 の時点で、メソッドの代わりにメソッドscope
を使用する新しいメソッドが呼び出されます。where
:conditions
年:
named_scope :active, :conditions => ["status = ?", "active"]
新しい:
scope :active, where(:status => "active")
また
scope :active, where("status = ?", "active")