ruby-on-rails - 具有单表继承的 Rails ActiveRecord_Associations_CollectionProxy

标签 ruby-on-rails ruby postgresql activerecord single-table-inheritance

我使用单表继承来模拟 Stores、Tailors、Orders 和 TailorOrders。订单属于裁缝,但我无法在 Rails 控制台中访问裁缝的订单。有多种类型的商店,在数据库中订单有一个 requester_id 和一个 provider_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" ...

这个错误似乎与数据库布局有关,正如我上面所描述的,其中 Tailor 类始终是订单数据库表中的 provider

有没有办法通过裁缝(一种商店,也是订单表中的供应商)访问订单?我还想完成的是类似于 Stores.first.orders.first.items 的内容。任何帮助将不胜感激谢谢!

最佳答案

我想我会在这里发布解决方案以防其他人遇到这个问题。根据@chumakoff 的评论,我只是像这样调整了 Tailor 类:

之前

class Tailor < Store 
  has_many :orders
end

之后

class Tailor < Store
  has_many :orders, foreign_key: "provider_id"
end

关于ruby-on-rails - 具有单表继承的 Rails ActiveRecord_Associations_CollectionProxy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44531131/

相关文章:

ruby http连接池

ruby-on-rails - 即时消息实现?

ruby-on-rails - 使足智多谋在 Controller 中起什么作用?

ruby-on-rails - 从子类中的重载方法调用基类方法

ruby-on-rails -/etc/environment 中的环境变量不能被 rails 访问

linux - PostgreSQL 集群启动竞争条件?

html - ERB 删除空行;不知道为什么

ruby - 将 cURL 请求转换为 Ruby post 请求

postgresql - 在 PostgreSQL 中如何操作多个子查询的执行顺序?

postgresql - Postgres Checkpointer 进程始终运行