Prevent change of one field in Rails model

With validates inclusion:

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

No need for additional method.


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

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