在Rails中,如何限制哪些属性可以更新,而不会阻止它们被创建?

我有一种情况,可以通过JSON API创建属性。 但是一旦它被创建,我想阻止它被更新。

这种约束导致我的第一个使用attr_accessible解决方案不够用。 有没有一种很好的方法来处理rails中的这种情况,或者我是否必须在update方法中执行手动检查?

您可以使用attr_readonly ,这将允许在创建时设置值,但在更新时忽略。

例:

 class User < ActiveRecord::Base attr_accessible :name attr_readonly :name end > User.create(name: "lorem") > u = User.first => # > u.name = "ipsum" => "ipsum" > u.save => true > User.first.name => "lorem" 

据我所知,有一个很好的方法,你必须编写自定义filter

 before_update :prevent_attributes_update def prevent_attribute_updates %w(attr1, attr2).each do |a| send("#{attr1}=", send("#{attr1}_was")) unless self.send("#{attr1}_was").blank? end end