2009-08-25 6 views

答えて

17

あなたは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 

...またはあなたが(あなたが一つのモデルは、このデフォルトのスコープを持つべきではないと判断した場合には迷惑かもしれない)ActiveRecord::Base自体にdefault_scopeを設定できます

class ActiveRecord::Base 
    default_scope :conditions => ["status = ?", "active"] 
end 
class ExampleModel < ActiveRecord::Base 
end 

コメントにklochnerで述べたように、あなたはまた、例えば、activeという名前ActiveRecord::Basenamed_scopeを、追加することを検討することもできます。

class ActiveRecord::Base 
    named_scope :active, :conditions => ["status = ?", "active"] 
end 
class ExampleModel < ActiveRecord::Base 
end 
ExampleModel.active # Return all active items. 
+0

どのように3.2.8の通り、新方式ではなく:conditions

旧のwhere方法を使用していますscopeと呼ばれ、 ActiveRecord :: Baseの名前付きスコープについてプロジェクトが共有されれば、他の開発者を混乱させる可能性は低くなります。 – klochner

+0

@klochner、はい、良い点。 ExampleModel.activeのようなものを使うことは非常に表現力があります。 – molf

+0

もう少しクリーンアップするには、名前付き(または新しい既定の)スコープを持つActiveRecordからクラスを派生させ、そこからExampleModelを派生させることができます。新しい機能が明示的になりました。 – klochner

0

更新:named_scopeは、Railsの3.1のdeprecated/renamedました。

named_scope :active, :conditions => ["status = ?", "active"] 

新:

scope :active, where(:status => "active") 

または

scope :active, where("status = ?", "active") 
関連する問題