Ruby 新人问个很傻很天真的问题

metal · December 29, 2011 · Last by fredwu replied at February 04, 2012 · 3787 hits

我想知道浏览次数是怎么实现的,我这个字段怎么写? integer 还是 string?

我能想到的就是 建立一个这样的字段

click_count:integer      :defualt => 0

然后

def show
   Post.click_count += 1 
end

可行吗??

应该是用 integer 吧。

不建议把这种经常变化的字段和不经常变的字段放在一张表里,这样会导致 mysql 的 query cache 失效,posts 表很大的时候,就会影响效率;保存时还可能会有很多 callback 会被执行,比如 before_save、更新 updated_at 等,可能导致 lz 不期望的后果。

PS:那个 click_count 是实例方法,用在了类上面。。。

integer

ActiveRecord 有 increment_counter 方法在数据库层面操作,避免并发冲突

http://apidock.com/rails/ActiveRecord/CounterCache/increment_counter

更新字段时,使用 Model.update_all 就可以避免执行 callback

increment_counter 内部也是用的 update_all

#2 楼 @Rei increment_counter 不会调用任何 callback,这在使用缓存的时候无法让缓存自动过期,好烦躁

#4 楼 @hooopo 我觉得阅读量也没必要适时显示吧?如果非要适时显示,可以往 redis 里读写,然后一段时间同步到数据库中。或者就直接放在 redis 里。

大流量的网站,记得用 INSERT DELAYED (http://dev.mysql.com/doc/refman/5.5/en/insert-delayed.html) 来避免性能瓶颈。

huacnlee in 提问要有方法 mention this topic. 03 Apr 10:56
You need to Sign in before reply, if you don't have an account, please Sign up first.