views:

36

answers:

2

Right now my classes are 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 inherite activer record into one class and than want to inherite that class into other classes like.

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
A: 

You can create module (e.g. lib/common_active_record.rb):

module CommonActiveRecord
  def before_validation
    set_blank_attributes_to_nil(@attributes)
  end
end

And then in your model simply include it:

class BalanceName < ActiveRecord::Base
  include CommonActiveRecord
end

class Balance < ActiveRecord::Base
  include CommonActiveRecord
end
lest
+1  A: 

You can do exactly as you have done except you do not need to redefine the before_validation methods in your subclasses (though I guess these may be here prior to being filled with more specific validation).

You will also need to indicate to rails that your CommonActiveRecord class is abstract and therefore is not persisted by adding:

class CommonActiveRecord < ActiveRecord::Base
  self.abstract_class = true
end
Shadwell