2009-11-06 81 views

回答

8

我做到這一點的把這個代碼lib/has_common_named_scopes.rb

module HasCommonNamedScopes 
    def self.included(base) 
    base.class_eval { 
     # Named scopes 
     named_scope :newest, :order => "#{base.table_name}.created_at DESC" 
     named_scope :freshest, :order => "#{base.table_name}.updated_at DESC" 
     named_scope :limit, lambda { |limit| {:limit => limit} } 
    } 
    end 
end 

,然後包括在各型號的模塊,我需要他們:

class MyModel < ActiveRecord::Base 
    include HasCommonNamedScopes 

我建議你使用base.table_name來在引用這些命名範圍中的列時限定表格,就像我在示例中所做的那樣。否則,當您將這些指定的作用域與其他連接到其他表的作用域相結合時,會遇到模糊引用的問題。

更新:

scope用Rails> 3使用和named_scope在以前的版本中使用。

1

還有Thoughtbot's Pacecar,增加了一幫很常見的命名範圍的每一個模型。它可能會與你正在尋找的東西一起出現。如果你需要自定義的東西,但是,Casper Fabricius有正確的想法。

0

對於Rails4項目,我通過擴展ActiveRecord::Base實現這一點,所有的類Rails模型繼承,在初始化(猴修補方案,要小心)

# in /config/initializers/shared_scope_initializer.rb 
module SharedScopes 
    extend ActiveSupport::Concern 

    module ClassMethods 
    def named_scope 
     return where(attribute: value) # query here 
    end 
    end 
end 

ActiveRecord::Base.send(:include, SharedScopes) 
相關問題