Question

I want to protect rails model attributes from being changed, only after the model enter certain state (eg. sign_in_count > 1). Looked around and see people using

attr_readonly

to protect the attributes, can I use it with condition? If not, is there alternative solution? Thanks.

Was it helpful?

Solution

I don't really understand what you want to do, so here are some general but related purpose. Btw, in rails 4 the attributes are protected, but you can use protected_attributes gem to go through rails 3 behaviour.

Btw, in ruby you can use freeze method can be invoked to prevent from any modifications of some object you have frozen. (Toc check wether the object is indeed frozen, you can call frozen? on that object and this will return true or false).

Another remark is that you can check some change state of your model by calling changed—attributes, this returns a Hash of fields that changed relatively to their original values.

Edit : you can of course set this statement

attr_readonly :some, :attributes unless some_condition

and define

def some_condition
   sign_in_count > 1
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top