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

后端 未结 2 904
粉色の甜心
粉色の甜心 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:46

    You can use attr_readonly, this will allow the value to be set on creation, but ignored on update.

    Example:

    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"
    

提交回复
热议问题