如何防止在Rails中更新单个属性?
提交表单时,如何防止在Rails中更新单个属性? 应更新所有其他属性。
是before_save
, attr_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) )