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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With