协会澄清

问题描述 投票:0回答:1

我有以下关联

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')

但它并非如此简单,因为我必须遍历属于该用户的每个广告系列。正确吗?

解决此问题的最佳方法是什么?范围或实例方法也会更好吗?

ruby-on-rails ruby ruby-on-rails-4 associations
1个回答
4
投票

has_many :through association应该起作用:

has_many :through
© www.soinside.com 2019 - 2024. All rights reserved.