2010-08-27 103 views
3

现在我的类看起来像这样。继承rails中的active_record

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 

我想将activer记录继承到一个类中,而不是想将该类继承到其他类中。

我想要这样的东西。

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 
+0

您还需要指示轨道您CommonActiveRecord类是抽象的,因此不会通过增加持续。而我的其他班级将继承那个普通班级。在我的问题的第二个块中,我写了一个代码,我想要类似的东西。 – 2010-08-27 21:07:37

回答

2

你可以做完全一样,你有除了你不需要在你的子类中重新定义before_validation方法(虽然我猜这些可能在被更多特定的验证填充之前)。 @phil我想创造出继承ActiveRecord的一个通用类

​​
0

您可以创建模块(例如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