2012-09-26 65 views
0

我有以下的用戶對象與範圍:導軌:相關範圍用條件

Class User < ActiveRecord::Base 
    ... 
    scope :vendors, lambda { where(:user_type => 'v') } 
    scope :customers, lambda { where(:user_type => 'c') } 
    ... 

我想創建一個新的inactive範圍是表現不同的供應商與客戶,例如在僞代碼

scope :inactive, lambda { 
    if (:user_type => 'v') 
     where(some_condition_only_for_vendors) 

    elsif (:user_type => 'c') 
     where(different_condition_only_for_customers) 

    else 
     where(another_condition) 

    end 
    } 

這樣一來,我可以這樣做users.vendors.inactive獲得基於一組條件,並users.customers.inactive所有非活動的供應商,我們將根據另一組所有不活躍的客戶。

這是可能的還是有更好的方法來做到這一點?請注意,這裏有很多遺留代碼,因此實現繼承可能不可行。

謝謝!

回答

0

我立即看到的問題是您從類中調用範圍,並且沒有記錄實例來獲取user_type。

User.inactive 

所以,你可能有類似:

class User < ActiveRecord::Base 
    scope :inactive, lambda { |user_type| 
    case user_type 
    when 'v' 
     where(some_condition_only_for_vendors) 
    when 'c' 
     where(different_condition_only_for_customers) 
    else 
     where(another_condition) 
    end 
    } 

    def related_users 
    User.inactive(user_type).all 
    end 
end