Ruby on rails 带有单表继承的Rails ActiveRecord\u关联\u CollectionProxy

Ruby on rails 带有单表继承的Rails ActiveRecord\u关联\u CollectionProxy,ruby-on-rails,ruby,postgresql,activerecord,single-table-inheritance,Ruby On Rails,Ruby,Postgresql,Activerecord,Single Table Inheritance,我使用单表继承对门店、裁缝、订单和裁缝订单进行建模。订单属于裁缝,但我无法在rails控制台中访问裁缝的订单。有多种类型的商店,在数据库中,订单有一个请求者id和一个提供者id。裁缝与订单的关系将始终是提供者。继承模型如下所示: class Store end class Tailor < Store has_many :orders end class Order has_many :items end class TailorOrders belongs_to

我使用单表继承对门店、裁缝、订单和裁缝订单进行建模。订单属于裁缝,但我无法在rails控制台中访问裁缝的订单。有多种类型的商店,在数据库中,订单有一个请求者id和一个提供者id。裁缝与订单的关系将始终是提供者。继承模型如下所示:

class Store
end

class Tailor < Store 
  has_many :orders
end

class Order 
  has_many :items
end 

class TailorOrders
   belongs_to :tailor, class_name: "Tailor", foreign_key: "provider_id"
end

class Item 
  belongs_to :order
end
我可以获取属于订单的项目,如下所示:

Order.first.items
#=>  [#<Item:0x007fe9f0cc8f58
  id: 1,
  order_id: 1,
  name: "Grey Pants",
  created_at: Tue, 13 Jun 2017 17:50:57 UTC +00:00,
  updated_at: Tue, 13 Jun 2017 17:50:57 UTC +00:00,
  type_id: 1>]
而且,我可以从订单中获得裁缝:

Order.first.tailor
#=> #<Tailor:0x007fe9f214b8b8
 id: 3,
 company_id: 3,
 primary_contact_id: 3,
 phone: "2121468958",
 street1: "640 Bennie Way",
 street2: "Apt. 533",
 city: "Carliefurt",
 state: "New Mexico",
 zip: "42439-4809",
 country: "Ukraine",
 created_at: Tue, 13 Jun 2017 17:50:56 UTC +00:00,
 updated_at: Tue, 13 Jun 2017 17:50:56 UTC +00:00,
 type: "Tailor",
 name: "Joe's on Main Street">
但是,我不能得到属于裁缝的订单:

Tailor.first.orders 
#=> #<Order::ActiveRecord_Associations_CollectionProxy:0x3ff4f786e9e0>

Tailor.first.orders.first
#=> ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR:  column orders.tailor_id does not exist
LINE 1: SELECT  "orders".* FROM "orders" WHERE "orders"."tailor_id" ...
这个错误似乎与数据库布局有关,正如我前面所描述的,其中类裁剪器始终是order的db表中的提供者

有没有一种方法可以通过一个定制店(一种类型的商店,同时也是订单表中的供应商)来访问订单?我还想完成的是类似于Stores.first.orders.first.items的东西。任何帮助都将不胜感激,谢谢

为AddTailor订单创建迁移。应该是这样的

rails g迁移addTailor订单定制:参考

类AddTailorReferenceToOrders
这将在Order表中创建一个列TAILER\u id,该表引用了TAILER。

我想我会在这里发布解决方案,以防其他人遇到此问题。根据@chumakoff的评论,我简单地调整了裁缝类,如下所示:

以前

class Tailor < Store 
  has_many :orders
end
之后


为裁缝类中的has\u many:orders关联设置外键选项。现在它希望外键是orders表中的tailor_id列,这在您的情况下有所不同。orders表中是否有一列指向它所属的裁缝?@chumakoff it works!完美感谢订单的db模式确实有一个provider_id列,这在我们的案例中是必要的,因为裁缝店并不是唯一满足它的商店
class Tailor < Store
  has_many :orders, foreign_key: "provider_id"
end