Edge Rails, Rails

[Edge Rails] 部分的なアップデート: Partial Updates

2008/04/03

Ryan’s Scraps / What’s New in Edge Rails: Partial Updates の抄訳です。

前回の Dirty Objects の機能追加の際、ActiveRecord で部分的なアップデートが可能となりました。たとえば、

article = Article.find(:first)
article.title  #=> "Title"
article.subject  #=> "Edge Rails"
 
# ひとつの属性をアップデート
article.title = "New Title"
 
# save時にDB にはこの属性のみアップデートを行います
article.save
  #=>  "UPDATE articles SET title = 'New Title' WHERE id = 1"

実はいままで知らなかったのですが、以前まではtitleだけでなく、変更していないsubjectまで含めたSQLを吐いていたんですね。これでSQLをスリムにできそうです。

またRails には、updated_at/on という特別なフィールド名がありますが、なにかしら属性が変更されていれば、このフィールドも自動的に更新されることになります(変更されてなければ SQL は発行されません)。

この機能を有効にするには、該当するモデル(app/model/article.rb)に対して、下記の1行を追加します。

ActiveRecord::Base.partial_updates = true

Edge Rails には、config/initializers/new_rails_defaults.rb にこの行が下記の通り書かれています。

# These settins change the behavior of Rails 2 apps and will be defaults
# for Rails 3. You can remove this initializer when Rails 3 is released.
 
# Only save the attributes that have changed since the record was loaded.
ActiveRecord::Base.partial_updates = true
 
# Include ActiveRecord class name as root for JSON serialized output.
ActiveRecord::Base.include_root_in_json = true
 
# Use ISO 8601 format for JSON serialized times and dates
ActiveSupport.use_standard_json_time_format = true

related posts


tags




have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

:

:


« [Edge Rails] ARオブジェクトの状態を知る: Dirty Objects
» ヤン富田 山本義隆 山形浩生