导轨型号 - 两个表具有相同的主键和外键的字段 [英] rails models - two tables have the same primary and foreign key fields

查看:165
本文介绍了导轨型号 - 两个表具有相同的主键和外键的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了Rails应用程序的现有数据库。

I am using an existing database with a rails app.

我不能更改表或列名。

I can't change the table or column names.

让我们说表中的一个是发票和表2是订单

Lets say table one is "invoices" and table 2 is "orders"

他们都有一个主键调用的同样的事情,可以说的order_id

they both have a primary key that is called the same thing, lets say "order_id"

发票可通过查看主键的order_idOrders表找到它的顺序。

invoices can find its order by looking at the primary key "order_id" in the orders table.

(或相反)的顺序找到自己的发票。

Vice versa for an order finding its invoice.

发票可以有,但并不总是有一个订单(你可能会开具发票以外的东西的顺序,如work_order,这将通过在work_orders表的主键位置寻找的order_id找到所以发票可能有一个work_order或订单。

Invoices can have but not always have one order (you might be invoiced for something besides an order, like a "work_order" which would be found by looking for the "order_id" in the primary key position of the "work_orders" table. So invoices might have a work_order or an order.

订单总是有发票 work_orders总是有发票

orders always has an invoice work_orders always has an invoice

我试着去找出类的车型。

Im trying to figure out the classes in the models.

你设置主键和外键同样的事情?什么belongs_to的?这个数据库建立的方式,没有真正属于什么,他们只是相互引用此相同的值的order_id。会是这样吗?

Do you set the primary and foreign keys to the same thing? What about belongs_to? The way this DB is set up, nothing really belongs to anything, they just reference each other by this same value "order_id". Would it be like this?

class Invoice < ActiveRecord::Base
    set_primary_key(:order_id)
    set_foreign_key(:order_id)
end

- 喀嚓 -

-- snip --

class Order < ActiveRecord::Base
    set_primary_key(:order_id)
    set_foreign_key(:order_id)
end

...且同为一个工单。

... And the same for a work order.

class WorkOrder < ActiveRecord::Base
    set_primary_key(:order_id)
    set_foreign_key(:order_id)
end

这是正确的?这似乎没用的方式做到这一点,但这DB是可怕的。

Is this correct? It seems to trashy of a way to do it but this DB is terrible.

那么所有belongs_to的东西吗?

What about all the belongs_to stuff?

让我知道如果我离开任何东西了。

Let me know if I have left anything out.

谢谢!

推荐答案

我相信答案可能是:

class Order < ActiveRecord::Base
    set_primary_key(:order_id)
    belongs_to :invoice, :foreign_key => :order_id
end

class WorkOrder < ActiveRecord::Base
    set_primary_key(:order_id)
    belongs_to :invoice, :foreign_key => :order_id
end

class Invoice < ActiveRecord::Base
    set_primary_key(:order_id)
    has_one :work_order
    has_one :order
end

虽然我真的不知道你的主键,也可以是一个外键(我是新来的Rails太)

Although I'm not really sure your primary key can also be a foreign key (I'm new to Rails too)

这篇关于导轨型号 - 两个表具有相同的主键和外键的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆