如何找到一个演出在 Rails 4 中的总下载次数?

How to find the total number of downloads a gig had in Rails 4?

这是我的模特关系

对于Purchase.rb

class Purchase < ActiveRecord::Base
  belongs_to :gig
  belongs_to :buyer, class_name: 'User'
  belongs_to :seller, class_name: 'User'
end

对于User.rb

class User < ActiveRecord::Base
  has_many :purchases, foreign_key: 'buyer_id'
  has_many :gigs, through: :purchases, source: :buyer
  has_many :gigs
  has_many :sales, foreign_key: 'seller_id', class_name: 'Purchase'
end

对于Gig.rb

class Gig < ActiveRecord::Base
  has_many :purchases
  has_many :buyers, through: :purchases
  has_many :sellers, through: :purchases
  belongs_to :user
end

现在我可以做到了

1.current_user.gigs.count 显示 current_user

上传的演出数量

2.current_user.purchases.count 显示 current_user 的下载次数。

3.@gig.purchases.count所选演出的下载次数

Question: If a user uploads a gig,as in code 3 above,i can show the number of times this gig was downloaded,but now I want to show if the user lets say uploads 3-7 gigs,i want to show the whole number of downloads he got,from all of his gigs.

我考虑过类似的事情 current_user.gigs.purchases.count,计算他所有演出获得的所有下载量。

您应该可以直接通过用户的购买查询金额并求和,如下所示:

current_user.gigs.map{|gig| gig.purchases.size}.sum

或在您的模型中 user.rb

def total_gigs_sold
  gigs.map{|gig| gig.purchases.size}.sum
end

你也应该明智地选择你的名字。每次下载都是一次购买吗? 这么说是不是很容易

current_user.sales.size

与演出的销售(/下载)次数相同吗?

使用计数器缓存可能会更好,因为它会减少数据库调用的次数。

class Order < ActiveRecord::Base
  belongs_to :customer, counter_cache: :count_of_orders
end
class Customer < ActiveRecord::Base
  has_many :orders
end