Inherit active_record in rails

Now my classes look like this.

class BalanceName < ActiveRecord
    def before_validation
      set_blank_attributes_to_nil(@attributes)
    end
end

class Balance < ActiveRecord
    def before_validation
      set_blank_attributes_to_nil(@attributes)
    end
end

I want to inherit the activator entry in one class and I do not want to inherit this class in other classes.

I want something like this.

class CommonActiveRecord < ActiveRecord::Base

  def before_validation
    set_blank_attributes_to_nil(@attributes)
  end

end

class BalanceName < CommonActiveRecord
    def before_validation
      super
    end
end

class Balance < CommonActiveRecord
    def before_validation
      super
    end
end
+3
source share
2 answers

You can do what you did, except that you do not need to override the methods before_validationin your subclasses (although, I think, they may be here before completing a more specific check).

You also need to tell the rails that your class CommonActiveRecordis abstract and therefore not persisted by adding:

class CommonActiveRecord < ActiveRecord::Base
  self.abstract_class = true
end
+2
source

(, lib/common_active_record.rb):

module CommonActiveRecord
  def before_validation
    set_blank_attributes_to_nil(@attributes)
  end
end

:

class BalanceName < ActiveRecord::Base
  include CommonActiveRecord
end

class Balance < ActiveRecord::Base
  include CommonActiveRecord
end
0

Source: https://habr.com/ru/post/1761993/


All Articles