12

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!

2 Answers 2

21

You want attr_readonly.

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't this deter Rails from updating and saving the Model back to the DB?
nice - didn't know the method existed ;) @Gishu no i don't think it would block saving model - it would just ignore changes to the fields listed in *attributes
Is this method only available in Rails 2.*? I am running in Rails 1.2.6.
Not sure. Look it up. Add it in if it isn't. :)
5

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.