Rails - 总和的counter_cache

时间:2014-03-26 09:26:05

标签: ruby-on-rails ruby-on-rails-3

我有Transactions表,它是UsersProducts之间的M:M表。

class Transaction
  belongs_to :user
  belongs_to :product, counter_cache: :transactions_count
end

在内部交易表中,我有quantity列。

在产品内部,我transactions_count存储了此产品的购买次数。

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

我知道我可以使用类似after_save :update_count的内容,但是有一个 Rails惯例,如果遵循这个会自动执行此任务吗?

由于

1 个答案:

答案 0 :(得分:3)

我个人认为counter_cache非常不可靠(给出负值等),并且往往会回避直到它得到改善

您可能感兴趣的内容:


Alias Column

We wanted to do something similar (pull from join model),发现一种可靠的方法是使用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 Association Extension

在发现.delegate方法之后,我想看看我们是否可以为连接模型实现类似的东西。 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

这基本上将我们的连接模型(image_messages)中的属性连接到父对象(image)。您可以使用它来汇总quantityproxy_association集合中的product,并附加到用户拥有的每个{{1}}

相关问题