2

I have a situation where an attribute can be created through a JSON API. But once it is created, I want to prevent it from ever being updated.

This constraint causes my first solution, which is using attr_accessible, to be insufficient. Is there a nice way to handle this type of situation in rails, or do I have to perform a manual check in the update method?

4

2 回答 2

4

您可以使用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"
于 2012-12-06T02:36:00.443 回答
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
于 2012-12-06T02:24:25.593 回答