模型中的Ruby on Rails增量计数器 [英] Ruby on Rails Increment Counter in Model

查看:141
本文介绍了模型中的Ruby on Rails增量计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从其他模型递增User表中的计数器.

I'm attempting to increment a counter in my User table from another model.

class Count < ActiveRecord::Base
    belongs_to :user

    after_create :update_count

    def update_count
        user = User.find(self.user_id)
        user.increment(:count)
    end

end

因此,创建计数时,目标是为该用户增加计数器列.目前,它拒绝在创建后获取用户,并且出现nil错误.

So when count is created the goal would be to increment a counter column for that user. Currently it refuses to get the user after creation and I get a nil error.

我正在为用户使用设备

这是正确的(最佳实践)场所吗?我让它在控制器中正常工作,但想对其进行清理.

Is this the right (best practice) place to do it? I had it working in the controllers, but wanted to clean it up.

我对Model回调没有经验.

I'm very inexperienced with Model callbacks.

推荐答案

如果User有很多Counts,而Count属于User(好像是),那么您可能想要使用计数器缓存.它完全可以完成您想做的事情,并且内置在ActiveRecord中.

If User has many Counts and Count belongs to User (like it seems to be), then you might want to use a counter cache. It does exactly what you want to do, and it is built-in into ActiveRecord.

这篇关于模型中的Ruby on Rails增量计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆