Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails attr_readonly doesn't work

According to this question and the documentation of attr_readonly the following should be possible:

class MyModel < ActiveRecord::Base
  attr_accessible :foo
  attr_readonly :bar
end

m = MyModel.create(foo: '123', bar: 'bar') # Should work
m.update_attributes(bar: 'baz')            # Should not work

However the first one fails, saying that I can't mass-assign bar. What am I mising?

like image 459
lucas clemente Avatar asked Jul 08 '12 12:07

lucas clemente


2 Answers

From documentation

attr_accessible takes a list of attributes that will be accessible. All other attributes will be protected.

So attr_accessible made bar attribute as protected from mass-assignment.

like image 59
megas Avatar answered Oct 22 '22 11:10

megas


You can make the attribute , suppose ,key as:-

attr_accessible :key

and then add one more validation

validate :check_if_key_changed, :on=> :update

private
def check_if_key_changed
  if self.key_changed?
    errors.add(:key,"cant change key")
  end
end

In this way you will be able to mass-assign it once on creation and can also make sure that it do not get updated.

like image 23
Nikita Singh Avatar answered Oct 22 '22 10:10

Nikita Singh