我想弄清楚是否有一种方法可以重用 AR 调用中的范围。这是我的例子
@current_account.items.report_by_month(month, year)
在 report_my_month 范围内,我想重用 @current_account
def self.report_by_month(month, year)
values = Values.where(:current_account => USE SCOPE FROM SELF)
scope = scoped{}
scope = scope.where(:values => values)
end
这只是了解如何执行此操作的示例代码,因为查询要复杂得多,因为它是一份报告。谢谢!
最佳答案
有什么理由不能简单地将它作为附加参数传递?
def self.report_by_month(month, year, current_account)
values = Values.where(:current_account => current_account)
scope = scoped{}
scope = scope.where(:values => values)
end
调用
@current_account.items.report_by_month(month, year, @current_account)
编辑:
如果您只是想避免再次传递@current_account,我建议为此在您的 Account 类中添加一个实例方法。
class Account
has_many :items
def items_reported_by_month(month, year)
self.items.report_by_month(month, year, id)
end
end
然后你可以调用它
@current_account.items_reported_by_month(month, year)
关于ruby-on-rails - Rails 3 - 访问范围链以重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815206/