Ruby on rails Rails-计数器\u缓存用于总和

Ruby on rails Rails-计数器\u缓存用于总和,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有交易表,它是用户和产品之间的M:M表 class Transaction belongs_to :user belongs_to :product, counter_cache: :transactions_count end 在交易表中,我有数量列 在产品内部,我有交易记录\u count,其中存储了购买该产品的次数 但该计数器缓存只计算行数。有没有办法计算数量之和 我知道我可以在保存后使用:update\u count,但是是否有一个Rails约定,当遵循该约定时将自动执行此任

我有
交易
表,它是
用户
产品
之间的M:M表

class Transaction
  belongs_to :user
  belongs_to :product, counter_cache: :transactions_count
end
在交易表中,我有
数量

在产品内部,我有
交易记录\u count
,其中存储了购买该产品的次数

但该计数器缓存只计算行数。有没有办法计算数量之和

我知道我可以在保存后使用
:update\u count
,但是是否有一个Rails约定,当遵循该约定时将自动执行此任务


谢谢

我个人发现
计数器缓存
非常不可靠(给出负值等),并且在改进之前倾向于回避

您可能感兴趣的内容:


别名列

,并发现一种可靠的方法是使用SQL别名列:

#app/models/user.rb
has_many :transactions
has_many :products, -> { select("#{User.table_name}.*, SUM(#{Transaction.table_name}.quantity) AS total") }, through: :transactions, dependent: :destroy
这可能需要一些工作,但会有所帮助#


ActiveRecord关联扩展

在发现这个方法之后,我想看看我们是否可以为连接模型实现类似的东西。2周后,我们让它工作:

#app/models/message.rb
Class Message < ActiveRecord::Base
   has_many :image_messages
   has_many :images, through: :image_messages, extend: ImageCaption
end

#app/models/concerns/image_caption.rb
module ImageCaption

    #Load
    def load
        captions.each do |caption|
            proxy_association.target << caption
        end
    end

    #Private
    private

    #Captions
    def captions
        return_array = []
        through_collection.each_with_index do |through,i|
            associate = through.send(reflection_name)
            associate.assign_attributes({caption: items[i]}) if items[i].present?
            return_array.concat Array.new(1).fill( associate )
        end
        return_array
    end

    #######################
    #      Variables      #
    #######################

    #Association
    def reflection_name
        proxy_association.source_reflection.name
    end

    #Foreign Key
    def through_source_key
        proxy_association.reflection.source_reflection.foreign_key
    end

    #Primary Key
    def through_primary_key
        proxy_association.reflection.through_reflection.active_record_primary_key
    end

    #Through Name
    def through_name
        proxy_association.reflection.through_reflection.name
    end

    #Through
    def through_collection
        proxy_association.owner.send through_name
    end

    #Captions
    def items
        through_collection.map(&:caption)
    end

    #Target
    def target_collection
        #load_target
        proxy_association.target
    end

end
#app/models/message.rb
类消息proxy_association.target可能重复感谢您的回答。但据我所知,每次我们查询数据库时,它都会计算数量?这会消耗内存还是可以忽略不计?是的,它会消耗内存并增加额外的时间。这只是一个建议,以帮助提供一些想法。
计数器\u缓存
只是数据库中的一列,其中包含一个数字;所以我想你可以用你的
after\u update
的想法来更新数量列:)谢谢你,我想我会用
after\u update
after\u save
Np!实际上,我们制作了另一个脚本,用于操纵
proxy\u关联
对象。如果您愿意,您可以发布代码--这使用内存,而不是SQL。如果您愿意,您可以在此处发布:)