Skip to content

Commit

Permalink
update_attribute should not update readonly attributes
Browse files Browse the repository at this point in the history
[#5106 state:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information
Neeraj Singh authored and josevalim committed Jul 21, 2010
1 parent c96a505 commit 992711a
Show file tree
Hide file tree
Showing 5 changed files with 15 additions and 2 deletions.
2 changes: 2 additions & 0 deletions activerecord/lib/active_record/persistence.rb
Expand Up @@ -105,6 +105,8 @@ def becomes(klass)
# Updates a single attribute and saves the record without going through the normal validation procedure
# or callbacks. This is especially useful for boolean flags on existing records.
def update_attribute(name, value)
raise ActiveRecordError, "#{name.to_s} is marked as readonly" if self.class.readonly_attributes.include? name.to_s

changes = record_update_timestamps || {}

if name
Expand Down
8 changes: 7 additions & 1 deletion activerecord/test/cases/persistence_test.rb
Expand Up @@ -17,13 +17,14 @@
require 'models/minimalistic'
require 'models/warehouse_thing'
require 'models/parrot'
require 'models/minivan'
require 'models/loose_person'
require 'rexml/document'
require 'active_support/core_ext/exception'

class PersistencesTest < ActiveRecord::TestCase

fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts
fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, 'warehouse-things', :authors, :categorizations, :categories, :posts, :minivans

def test_create
topic = Topic.new
Expand Down Expand Up @@ -220,6 +221,11 @@ def test_update_attribute
assert !Topic.find(1).approved?
end

def test_update_attribute_for_readonly_attribute
minivan = Minivan.find('m1')
assert_raises(ActiveRecord::ActiveRecordError) { minivan.update_attribute(:color, 'black') }
end

def test_update_attribute_with_one_changed_and_one_updated
t = Topic.order('id').limit(1).first
title, author_name = t.title, t.author_name
Expand Down
1 change: 1 addition & 0 deletions activerecord/test/fixtures/minivans.yml
Expand Up @@ -2,3 +2,4 @@ cool_first:
minivan_id: m1
name: my_minivan
speedometer_id: s1
color: blue
5 changes: 4 additions & 1 deletion activerecord/test/models/minivan.rb
Expand Up @@ -3,4 +3,7 @@ class Minivan < ActiveRecord::Base

belongs_to :speedometer
has_one :dashboard, :through => :speedometer
end

attr_readonly :color

end
1 change: 1 addition & 0 deletions activerecord/test/schema/schema.rb
Expand Up @@ -300,6 +300,7 @@ def create_table(*args, &block)
t.string :minivan_id
t.string :name
t.string :speedometer_id
t.string :color
end

create_table :minimalistics, :force => true do |t|
Expand Down

0 comments on commit 992711a

Please sign in to comment.