From 406e79c768fd8a4929083e38453a4b8950b5e114 Mon Sep 17 00:00:00 2001 From: Indrek Juhkam Date: Tue, 1 Dec 2009 19:36:26 +0200 Subject: [PATCH] Added ActiveRecord#update_attribute! method. --- activerecord/lib/active_record/base.rb | 7 +++++++ activerecord/test/cases/base_test.rb | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 0 deletions(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 056f29f..c6926ef 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2573,6 +2573,13 @@ module ActiveRecord #:nodoc: save(false) end + # Updates a single attribute. Similar to the +update_attribute+ method, except this one goes through the normal validation procedure. + # An exception is raised if the record is invalid. + def update_attribute!(name, value) + send(name.to_s + '=', value) + save! + end + # Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will # fail and false will be returned. def update_attributes(attributes) diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 5c2911e..8af1bfc 100755 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -932,6 +932,22 @@ class BasicsTest < ActiveRecord::TestCase assert !Topic.find(1).approved? end + def test_update_attribute! + reply = Reply.find(2) + assert reply.approved? + assert_equal "The Second Topic of the day", reply.title + + reply.update_attribute!("title", "The Second Topic of the day updated") + reply.reload + assert_equal "The Second Topic of the day updated", reply.title + + reply.update_attribute!(:approved, false) + reply.reload + assert !reply.approved? + + assert_raise(ActiveRecord::RecordInvalid) { reply.update_attribute!(:title, nil) } + end + def test_update_attributes topic = Topic.find(1) assert !topic.approved? -- 1.6.3.3