Inherit active_record in rails
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 reco开发者_运维知识库rd 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
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
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
精彩评论