【问题标题】:Inherit active_record in rails在 Rails 中继承 active_record
【发布时间】:2011-04-05 00:31:44
【问题描述】:

现在我的课是这样的。

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

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

我想要这样的东西。

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

【问题讨论】:

  • @phil 我想创建一个继承 ActiveRecord 的通用类。而我的另一个类将继承该公共类。在我的问题的第二个块中,我编写了一个我想要类似的代码。

标签: ruby-on-rails ruby inheritance activerecord


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    除了不需要在子类中重新定义 before_validation 方法之外,您可以完全按照您的方式进行操作(尽管我猜这些可能在填充更具体的验证之前就在这里)。

    您还需要向 rails 表明您的 CommonActiveRecord 类是抽象的,因此不会通过添加:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      相关资源
      最近更新 更多