计算所有关联对象并更新计数器

时间:2016-08-22 02:11:49

标签: ruby-on-rails activerecord

我有2个型号:

$("button").click(function(){
    $.post("/", { url: $('#urlimg').val()}, function(data, status){
        alert("message: " + data.message + "\nURL: " + data.url + "\nStatus: " + status);
    });
});

产品型号有一列class Products < ActiveRecord::Base has_many :purchases class Purchase < ActiveRecord::Base belongs_to :Product

我想要一种非常快速有效的方法来更新这个基本上运行这个sql的计数器:

purchase_count

我可以使用ActiveRecord执行此操作吗?如果没有,我怎么能用原始的sql做到这一点?

1 个答案:

答案 0 :(得分:2)

您应该使用counter_cache列来提高效率。 Rails允许您在counter_cache模型(true)中将belongs_to选项设置为purchase。但是您应该生成一个迁移以向products表添加一列。

有关详情,请在http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference

中查找counter_cache

如果您只是不想计算所有关联的对象而需要传入条件,则需要自定义 counter cache。请查看http://douglasfshearer.com/2006/10/06/custom-counter-cache-with-conditions.html示例。