【问题标题】:Adding find condition to all Active Record Models in Rails向 Rails 中的所有 Active Record 模型添加查找条件
【发布时间】:2010-11-22 12:59:57
【问题描述】:

是否有向所有活动记录模型添加查找条件?

就是我想要这个查询

ExampleModel.find :all, :conditions=> ["status = ?", "active"]

表现得和

一样
ExampleModel.find :all

在每个模型中

谢谢!!

【问题讨论】:

    标签: ruby-on-rails activerecord find conditional-statements


    【解决方案1】:

    你可以使用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 在评论中提到的,您可能还想考虑在ActiveRecord::Base 中添加一个named_scope,命名为active,例如:

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

    【讨论】:

    • ActiveRecord::Base 上的命名范围怎么样?如果项目被共享,这不太可能让其他开发人员感到困惑。
    • @klochner,是的,好点。使用像 ExampleModel.active 这样的东西非常有表现力。
    • 为了进一步清理它,您可以从 ActiveRecord 派生一个具有命名(或新默认)范围的类,并让 ExampleModel 从中派生。现在新功能是明确的。
    • 太棒了。感谢您的回答。不过还有一个问题。如何在允许向搜索添加更多条件的同时使用此命名路由?
    • @rube_noob:您可以链接命名范围(任意数量)和常规查找方法:ExampleModel.active.find(:conditions => ...)。
    【解决方案2】:

    更新: named_scope 在 Rails 3.1 中是 deprecated/renamed。从 3.2.8 开始,新方法称为 @987654322@,它使用 where 方法而不是 :conditions

    旧:

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

    新:

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

    或

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多