如何防止在Rails中更新单个属性?

提交表单时,如何防止在Rails中更新单个属性? 应更新所有其他属性。

before_saveattr_reader还是其他方式?

如果使用before_save ,如何访问属性hash?

Rails 3.0.7

查看attr_protected

 Class YourModel << ActiveRecord::Base attr_protected :the_one_column, as: :update # ... end 

现在,作为对update_attributes的调用的一部分,您可以指定:update role,例如

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

如果:the_one_column在传递给update_attributes params设置了:the_one_column ,则会抛出错误。

正如@Beerlington在对你的问题的评论中提到的那样,你也应该查看attr_accessible 。 通常使用attr_accessible将所有模型的应用程序白名单属性花费30分钟,而不是使用attr_accessible将特定属性列入黑名单attr_protected

其他选项只是在您的控制器中执行此操作:

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