诗歌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

 

转载于:https://www.cnblogs.com/orez88/articles/1793431.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值