Search code examples
ruby-on-railsactiverecordsingle-table-inheritance

How to override the attr_protected?


I have STI implementation as follows:

class Automobile < ActiveRecord::Base
end

class Car < Automobile
end

class Truck < Automobile
end

class User < ActiveRecord::Base
  has_many :automobiles
  accepts_nested_attributes_for :automobiles
end

I am creating a list of automobiles for a user. For each automobile, the UI sets the type field and the properties associated with the automobile.While form submission, the type field is ignored as it is a protected attribute.

How do I work around this issue? Is there a declarative way to unprotect a protected attribute?

Edit: This is my current solution for the problem: I override the attributes_protected_by_default private method in my model class.

class Automobile < ActiveRecord::Base
private
  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end
end

This removes the type field from the protected list.

I am hoping that there is a better way than this.


Solution

  • I ended up doing this:

    class Automobile < ActiveRecord::Base
    private
      def attributes_protected_by_default
        super - [self.class.inheritance_column]
      end
    end