【问题标题】:Overriding an inherited after_save function in ActiveRecord在 ActiveRecord 中覆盖继承的 after_save 函数
【发布时间】:2020-03-02 14:37:21
【问题描述】:

假设我有一个带有 after_save 方法的 Active Record 类,例如:

class Vehicle < ActiveRecord::Base
  after_save :wheel_count

  def wheel_count
    puts 4

(我知道这是糟糕的设计;这只是一个例子)

我有这个类的一个子类,我想用它覆盖after_save 方法:

class Boat < Vehicle
  def wheel_count
    puts 0

但是,似乎子函数没有被调用。有没有办法根据实例动态选择after_save 函数?我想我可以按照以下方式做一些事情:

after_save :after_save_handler

def after_save_handler
  wheel_count

但这似乎是一个糟糕的解决方案。

【问题讨论】:

    标签: ruby-on-rails ruby rails-activerecord


    【解决方案1】:

    您可以使用STISingle Table Inheritance 执行此操作。

    Active Record 通过将类的名称存储在默认命名为“type”的列中来允许继承(可以通过覆盖 Base.inheritance_column 来更改)。这意味着继承看起来像这样:

    class Company < ActiveRecord::Base; end
    class Firm < Company; end
    class Client < Company; end
    class PriorityClient < Client; end
    

    当您执行Firm.create(name: "37signals") 时,此记录将保存在companies 表中,类型=“Firm”。然后,您可以使用Company.where(name: '37signals').first 再次获取该行,它将返回一个Firm 对象。

    您可以轻松地覆盖子类中的父类方法,当这些方法被调用时,它们会根据对象的类型做出响应。你可以在这里详细阅读 - Single Table Inheritance

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-04
      • 2019-06-29
      相关资源
      最近更新 更多