2012-03-06 47 views
1

目前我建立這樣的查詢:從模型中獲取範圍中的ActiveRecord

account.sales.method_needing_more_account_info(account) 

我想基於這樣已經存在,簡化了方法的範圍,能夠確定帳戶呼籲喜歡的東西這:

account.sales.method_pulling_account_from_scope 

我這樣做是因爲帳戶模型持有某些設置,確定如何呈現銷售數據並更改匹配的查詢。

回答

1

作用域是類方法因此不知道實例變量和屬性,以便做你要求你必須堅持你的第一個代碼示例。

的替代方案將是寫一個返回數據

軌道2

# returns an array of results 
def more_account_info 
    self.sales.all(:conditions => []) 
end 

# i've also added an initializer to allow for returning a scope before 
# details here: http://railscasts.com/episodes/112-anonymous-scopes 
class ActiveRecord::Base 
    scope :conditions, lambda { |*args| {:conditions => args} } 
end 

# which allows for me to return a scoped object (chainable) 
def more_account_info 
    scope = Account.scoped({}) 
    scope = scope.sales 
    scope = scope.conditions "" 
end 

或在軌道3,你可以返回一個阿雷爾對象(環連接)

滑軌的方法3

# returns an arel object rather than an array of results 
def more_account_info 
    self.sales.where("") 
def 
+0

導軌3的方法似乎是最好的。謝謝! – iterion 2012-04-11 18:28:39