【发布时间】:2016-07-01 05:05:17
【问题描述】:
我想知道是否有办法在 ActiveRecord::Relation 中访问关联的 belongs_to 对象
例如在这种关系中:
class Customer < ActiveRecord::Base
has_many :invoices
end
class Invoice < ActiveRecord::Base
belongs_to :customer
def self.check_new
# do something
rescue => e
MyLogger.log_error_for(customer, __method__)
end
end
所以如果我打电话给
Customer.first.invoices.check_new
并发生错误。我想为这个特定的客户记录这个错误。
我知道我可以在类方法中使用scoped 获取发票并调用scoped.first.customer。
但这似乎有点脏。此外,如果还没有任何发票,这将不是一个解决方案。
我不知道是否有办法做到这一点,但对 scoped 的检查会给你类似的东西:
SELECT * FROM SOME JOIN WHERE customer_id = 1
所以有一种对 Customer 对象的引用。 有人可以帮忙吗?
更新: 这只是一个例子。其实我不做日志记录什么的。当然,它们是进行日志记录的更好方法。 我想要的只是将更新集合的代码放在模型类中。就像普通的 Customer.first.invoices.create 一样。并且可以访问此关系的父级。
【问题讨论】:
标签: ruby-on-rails activerecord