Rails Model: How to make a attribute protected or

2019-07-28 01:05发布

问题:

There are some fields present in table which i don't want to be visible outside?

Like created_on, is_first etc. I want to set value of these fields by using callbacks with in model but not accessible for some one to set it.

回答1:

The standard way to prevent mass-assignment on certain fields is attr_protected and attr_accessible:

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

In your case, you would have to add this line in your model:

attr_protected :created_on, :is_first

Even if you have a form with these fields, their values will be ignored, when used in a new/create call.



回答2:

def is_new =(is_new)
     raise 'is_new is immutable!'
end