In Rails, how do I limit which attributes can be updated, without preventing them from being created?

后端 未结 2 857
粉色の甜心
粉色の甜心 2021-01-24 11:27

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

2条回答
  •  清酒与你
    2021-01-24 11:49

    There is not a nice way to do that as far as I know, you have to write a custom 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
    

提交回复
热议问题