How to prevent updating a single attribute in Rails?

别说谁变了你拦得住时间么 提交于 2019-12-11 10:31:34

问题


When a form is submitted, how to prevent a single attribute from being updated in Rails? All other attributes should be updated.

Is it before_save, attr_reader or some other way?

If using before_save, how to access to the attributes hash?

Rails 3.0.7


回答1:


Check out attr_protected.

Class YourModel << ActiveRecord::Base

  attr_protected :the_one_column, as: :update

  # ...
end

Now as part of a call to update_attributes, you'd specify the :update role, for example

klass = YourModel.find(some_id)
klass.update_attributes(params[:your_model], as: :update)

If :the_one_column is set in params passed to update_attributes, it will throw an error.

As @Beerlington mentioned in his comment to your Question, you should also check out attr_accessible. It's generally better to spend the 30 minutes going through all models of your application white-listing attributes using attr_accessible than it is to blacklist specific attributes with attr_protected.




回答2:


Other option is simply doing this in your controller:

klass.update_attributes( params[:your_model].except(:attributes_to_avoid) )


来源:https://stackoverflow.com/questions/12020296/how-to-prevent-updating-a-single-attribute-in-rails

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