ruby-on-rails - Rails 3 - 访问范围链以重用

标签 ruby-on-rails activerecord scope

我想弄清楚是否有一种方法可以重用 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/

相关文章:

ruby-on-rails - '警告: Non-executables were installed to "bin" ' when installing elasticsearch via homebrew

javascript - Encodeuricomponent 在 rails 中解码它

php - Codeigniter ActiveRecord,按类别统计记录

javascript - jquery 函数范围内类的 TypeScript 调用方法

c - 返回指针的函数

ruby-on-rails - 如何将程序包添加到现有图像?

ruby-on-rails - 在 Rails 中将 delayed_job 用于 Mechanize 脚本(NoMethodError : undefined method for nil:NilClass)

sql - 尽管有缓存,搜索查询的性能还是被共同好友限制了 98%

mysql - 为什么 ActiveRecord 和/或 MySQL 对此字符有问题?

javascript - jQuery 插件 : variable scope issue between plugins