Rails Model: How to make a attribute protected or private that is not visible outside model?

谁说胖子不能爱 提交于 2019-12-24 16:27:14

问题


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


来源:https://stackoverflow.com/questions/5465628/rails-model-how-to-make-a-attribute-protected-or-private-that-is-not-visible-ou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!