作者:Ryan Daigle 来源:JavaEye 酷勤网收集 2008-05-29
摘要
新的rails中activerecord拥有了检查record object是否有改变的能力,即dirty object. 你可以直接查询对象所有改变了的属性,如果你要使用attr=以外的方法改变对象属性的时候,可以使用attr_name_will_change!来告诉对象注意属性的变化
系列文章汇总《Ruby on Rails 2.1新特性》
新的rails中activerecord拥有了检查record object是否有改变的能力,即dirty object.
这个功能非常简单灵活:
- article = Article.find(:first)
- article.changed? #=> false
- # Track changes to individual attributes with
- # attr_name_changed? accessor
- article.title #=> "Title"
- article.title = "New Title"
- article.title_changed? #=> true
- # Access previous value with attr_name_was accessor
- article.title_was #=> "Title"
- # See both previous and current value with attr_name_change accessor
- article.title_change #=> ["Title", "New Title"]
article = Article.find(:first) article.changed? #=> false # Track changes to individual attributes with # attr_name_changed? accessor article.title #=> "Title" article.title = "New Title" article.title_changed? #=> true # Access previous value with attr_name_was accessor article.title_was #=> "Title" # See both previous and current value with attr_name_change accessor article.title_change #=> ["Title", "New Title"]
你还可以直接查询对象所有改变了的属性,(继续上例):
- # Get a list of changed attributes
- article.changed #=> ['title']
- # Get the hash of changed attributes and their previous and current values
- article.changes #=> { 'title' => ["Title", "New Title"] }
# Get a list of changed attributes
article.changed #=> ['title']
# Get the hash of changed attributes and their previous and current values
article.changes #=> { 'title' => ["Title", "New Title"] }
注意: 如果你保存了一个dirty object,他就会清除所有改变的痕迹:
- article.changed? #=> true
- article.save #=> true
- article.changed? #=> false
article.changed? #=> true article.save #=> true article.changed? #=> false
如果你要使用attr=以外的方法改变对象属性的时候,可以使用attr_name_will_change!来告诉对象注意属性的变化:
- article = Article.find(:first)
- article.title_will_change!
- article.title.upcase!
- article.title_change #=> ['Title', 'TITLE']
article = Article.find(:first) article.title_will_change! article.title.upcase! article.title_change #=> ['Title', 'TITLE']
原文:http://ryandaigle.com/
来自:http://www.javaeye.com/news/2349


