gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:09 24 4
gpt4 key购买 nike

我使用单表继承来模拟 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com