我有以下关联
User - has_many :campaigns
Campaign - has_many :donations
belongs_to :user
Donation - belongs_to :campaign
作为用户,我希望获得current_user创建的所有广告系列的所有捐款之和,所以我尝试了此操作
@campaigns = current_user.campaigns
@total_donations = @campaigns.dontations.sum('donation_amount')
但它并非如此简单,因为我必须遍历属于该用户的每个广告系列。正确吗?
解决此问题的最佳方法是什么?范围或实例方法也会更好吗?
has_many :through
association应该起作用:
has_many :through