我目前正在构建这样的查询:
account.sales.method_needing_more_account_info(account)
我希望能够根据已经存在的范围确定帐户,将方法调用简化为:
account.sales.method_pulling_account_from_scope
我这样做是因为帐户模型包含某些设置,这些设置决定了销售数据的呈现方式,并改变了要匹配的查询。
答案 0 :(得分:2)
范围是类方法,因此不知道实例变量和属性,为了做你要求你必须坚持你的第一个代码样本。
另一种方法是编写一个返回数据的方法
Rails 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
或在rails 3中,您可以返回一个Arel对象(可链接)
Rails 3
# returns an arel object rather than an array of results
def more_account_info
self.sales.where("")
def