【问题标题】:ruby active_record-acts_as gem: getting correct child from parent instanceruby active_record-acts_as gem:从父实例获取正确的子实例
【发布时间】:2016-01-20 21:13:58
【问题描述】:

我正在使用 active_record-acts_as gem 来实现多表继承。我的场景:

class Vehicle < ActiveRecord::Base
   actable
end

class Plane < ActiveRecord::Base
    acts_as :Vehicle
end

class Train < ActiveRecord::Base
    acts_as :Vehicle
end

每当我创建 Plane 或 Train 的实例时,都会创建相应的 Vehicle。

我正在开发一个 API,因此在列出车辆后,我将返回车辆模型中的字段。但是,当我收到 GET /Vehicles/1 时,我想退回实际车辆,无论是飞机、火车等。

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails inheritance dynamic polymorphism


    【解决方案1】:
    class VehiclesController
      def show
        @vehicle = Vehicle.find(params[:id]).specific
      end 
    end
    

    由于飞机和火车都“扩展”了 MTI 意义上的车辆,您可以通过查询 Vehicle 获得记录。 .specific 为您提供实际的 Plane 或 Train 实例,而不是父类型。

    【讨论】:

    • 没错!当我在 gem 的文档中阅读该方法时,我完全误解了它
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    相关资源
    最近更新 更多