我的情况是可以通过JSON API创建属性。但是一旦它被创建,我想阻止它被更新。
此约束导致我的第一个使用attr_accessible
的解决方案不足。有没有一种很好的方法来处理rails中的这种情况,或者我是否必须使用update
方法执行手动检查?
答案 0 :(得分:3)
您可以使用attr_readonly
,这样可以在创建时设置值,但在更新时会被忽略。
示例:
class User < ActiveRecord::Base
attr_accessible :name
attr_readonly :name
end
> User.create(name: "lorem")
> u = User.first
=> #<User id: 1, name: "lorem">
> u.name = "ipsum"
=> "ipsum"
> u.save
=> true
> User.first.name
=> "lorem"
答案 1 :(得分:0)
据我所知,有一个很好的方法,你必须编写一个自定义过滤器
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