Is there a better way to create read-only attributes in rails?

module, ruby, ruby-on-rails

Solution

Have you tried this:

class Model < ActiveRecord::Base    
  before_save :protect_attributes

  private
  def protect_attributes
     false if !new_record? && event_type_changed?
  end
end

Another thought is, why bother enforcing this at the model level? What is the difference between a read-only attribute and an attribute that can only be written to in the create action of your controller? You could always do this:

class EventController < ActionController::Base
  def create
    @event = Event.new params.require(:event).permit :event_name, :event_type
  end

  def update
    @event = Event.find(params[:id]).update params.require(:event).permit(:event_name)
  end
end

Problem

I'm creating an ActiveRecord object in Rails that I want to have read-only attributes. I initially tried using `attr_readonly` but was dismayed to find that it: - Disabled mass-updating of those properties, even on new records - Did not raise an exception if the record was saved, or notify you that a read-only property was being changed in any way. I want both of these features; this is my attempt at an implementation: ``` # For use with ActiveRecord module ReadOnlyAttributes class ReadOnlyAttributeException < StandardError end def create_or_update # Private, but its what every method gets funneled through. if !self.new_record? && self.respond_to?(:read_only_attributes) changed_symbols = self.changed.map(&:to_sym) if changed_symbols.intersect?(self.read_only_attributes) raise ReadOnlyAttributeException, "Readonly attributes modified on #{self.class}: #{changed_symbols & self.read_only_attributes}" end end super end end ``` And then in my model: ``` class Model < ActiveRecord::Base include ReadOnlyAttributes def read_only_attributes [:event_type] end end ``` Is there a built-in or better way to get read-only properties that meet the above requirements? I'm still pretty new to Ruby/Rails, so I would also appreciate any stylistic comments.

Original source

Related problems