Prevent change of one field in Rails model

前端 未结 3 1729
执念已碎
执念已碎 2020-12-14 08:06

I have two related models - let\'s say Activity and Step. Activity has_many :steps and Step belongs_to :activity which me

相关标签:
3条回答
  • 2020-12-14 08:50

    You can declare an attribute as read_only with attr_readonly :your_field_name. But this won't create an error if you try to write this attribute, it will fail silently. (This attribute will be ignored for all SQL-Updates)

    Another option might be, to write a validation for this case, might look like this:

    class Step < ActiveRecord::Base
      validate :activity_id_not_changed
    
      private
    
      def activity_id_not_changed
        if activity_id_changed? && self.persisted?
          errors.add(:activity_id, "Change of activity_id not allowed!")
        end
      end
    end
    

    persisted? returns true, if this is not a new record and it is not destroyed.

    Links:

    http://api.rubyonrails.org/classes/ActiveRecord/ReadonlyAttributes/ClassMethods.html#method-i-readonly_attributes

    http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-persisted-3F

    0 讨论(0)
  • 2020-12-14 09:06

    With validates inclusion:

      validates :activity_id,
                inclusion: { in: ->(i) { [i.activity_id_was] } },
                on: :update
    

    No need for additional method.

    0 讨论(0)
  • 2020-12-14 09:07

    I think you can do this too with the Hobo permissions system: http://hobocentral.net/manual/permissions

    For example:

    def update_permitted?
      acting_user.administrator && !activity_id_changed?
    end
    
    0 讨论(0)
提交回复
热议问题