诗歌rails 之 touch的用法

touch是Rails2.3.3引入的新功能,可以将指定的attributes改为当前时间,默认是更改updated_at或updated_on。

典型的用法在many-to-one时,当many端发生改变时,更新one端的updated_at时间。比如在一个论坛系统中,一个帖子的更新时间会随着之后的回复发生改变:

1.class Post < ActiveRecord::Base
2.has_many :replies
3.end
1.class Reply < ActiveRecord::Base
2.belongs_to :post:touch => true
3.end

这里声明的:touch => true,其实就是定义了一个method来更新Post的updated_at时间,并且在after_save和after_destroy的时候调用该method

01.def add_touch_callbacks(reflection, touch_attribute)
02.method_name ="belongs_to_touch_after_save_or_destroy_for_#{reflection.name}".to_sym
03.define_method(method_name) do
04.association = send(reflection.name)
05. 
06.if touch_attribute == true
07.association.touch unless association.nil?
08.else
09.association.touch(touch_attribute) unless association.nil?
10.end
11.end
12.after_save(method_name)
13.after_destroy(method_name)
14.end

 

posted @ 2010-08-05 18:25  麦飞  阅读(461)  评论(0编辑  收藏  举报