Prevent change of one field in Rails model

前端 未结 3 1730
执念已碎
执念已碎 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

提交回复
热议问题