Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to protect a Rails model attribute?

My Invoice model has an address_id attribute, and I don't want this address_id to change FOREVER. So I don't want this to happen outside the class:

invoice.address_id = 1
invoice.address = some_address

Rails automatically adds this address_id attribute to the model from the invoice table, so how can I declare this attribute private/protected? Calling

attr_protected :address_id

is most likely not the solution since based on the documentation it only prevents mass assignments.

Thanks!

like image 468
gsmendoza Avatar asked Sep 26 '08 03:09

gsmendoza


2 Answers

Not as pretty as a one liner, but code below should work (and you could always do some metaprogramming to write an 'immutable' method)

def address_id=(id)
  if new_record?
    write_attribute(:address_id, id)
  else
    raise 'address is immutable!'
  end
end 
like image 151
ryw Avatar answered Nov 15 '22 15:11

ryw


You want attr_readonly.

like image 24
Ian Terrell Avatar answered Nov 15 '22 16:11

Ian Terrell