rails models - two tables have the same primary and foreign key fields

℡╲_俬逩灬. 提交于 2019-12-23 05:02:12

问题


I am using an existing database with a rails app.

I can't change the table or column names.

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

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

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.

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.

orders always has an invoice work_orders always has an invoice

Im trying to figure out the classes in the models.

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

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

What about all the belongs_to stuff?

Let me know if I have left anything out.

Thanks!


回答1:


I believe the answer could be:

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

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



来源:https://stackoverflow.com/questions/3322512/rails-models-two-tables-have-the-same-primary-and-foreign-key-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!