对 Ruby on Rails 并不陌生,但从未真正处理过更复杂的 ActiveRecord 查询。
假设我有一个会员模型,它有_many 推荐的用户和推荐的用户有_many 购买的产品。
我想要做的是一种有效的 ActiveRecord 方法来获取所有推荐用户的购买产品总数。我该怎么做呢?
谢谢。
对 Ruby on Rails 并不陌生,但从未真正处理过更复杂的 ActiveRecord 查询。
假设我有一个会员模型,它有_many 推荐的用户和推荐的用户有_many 购买的产品。
我想要做的是一种有效的 ActiveRecord 方法来获取所有推荐用户的购买产品总数。我该怎么做呢?
谢谢。
假设对象如下:
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')