has_many关联的总和

时间:2013-07-15 19:12:32

标签: ruby-on-rails activerecord

Ruby on Rails并不陌生,但从未真正使用过更复杂的ActiveRecord查询。

假设我有一个Affiliate模型,其中has_many引用了用户并且推荐用户has_many purchase_products。

我想要做的是一种有效的ActiveRecord方式来获取所有被推荐用户的purchase_products数量的总和。我该怎么做呢?

感谢。

1 个答案:

答案 0 :(得分:2)

假设对象如:

class Affiliate < ActiveRecord::Base
  has_many :users
end

class Users < ActiveRecord::Base
  #should have purchased_products_count integer column
  belongs_to :affiliate
  has_many :pruchased_products
end

class PurchasedProducts < ActiveRecord::Base
  belongs_to :user, counter_cache: :purchased_products_count
end

products_count = User.first.purchased_products.size # uses counter_cache to get the size
another_products_count = User.first.purchased_products_count # get the value diretly
all_users_products_count = my_affiliate.users.map(&:purchased_products_count).inject(:+) # makes an array of product counts then sums them

我认为这可能也有效

my_affiliate.users.sum('purchased_products_count')