Ruby on rails 的总和有许多关联
RubyonRails并不陌生,但从未真正处理过更复杂的ActiveRecord查询 假设我有一个联盟模式,有很多被推荐的用户,被推荐的用户购买了很多产品 我想做的是一种高效的ActiveRecord方法,用于获取所有被推荐用户的已购买产品总数。我该怎么做呢 谢谢。假设对象如下:Ruby on rails 的总和有许多关联,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,RubyonRails并不陌生,但从未真正处理过更复杂的ActiveRecord查询 假设我有一个联盟模式,有很多被推荐的用户,被推荐的用户购买了很多产品 我想做的是一种高效的ActiveRecord方法,用于获取所有被推荐用户的已购买产品总数。我该怎么做呢 谢谢。假设对象如下: class Affiliate < ActiveRecord::Base has_many :users end class Users < ActiveRecord::Base #should
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
我已经有了一个类似的解决方案,我正在寻找一个ActiveRecord解决方案来在数据库中进行计算,而不是使用Ruby。编辑:抱歉,没有看到最后一行。不确定是否要添加另一列,是否可以执行purchased_products.count而不是缓存该列?计数器缓存的效率要高得多,这正是您想要的,因为它只是读取一列,而不必进行计数(*)并循环遍历表中的每一行。计数器缓存是否会自动适当地递增/递减?如果我只想计算在某个时间创建的已购买的产品的总和,例如,现在。月初?
my_affiliate.users.sum('purchased_products_count')