您可以使用STI方法(单继承表):
模型用户:
class User < ActiveRecord::Base
# general attributes and validations and the like
end
所有者型号:
class Owner < User
# specific attributes and/or validations if any
has_many :products
end
借款人模式:
class Borrower < User
# specific attributes and/or validations if any
haas_many :products
end
产品型号:
class Product < ActiveRecord::Base
# attributes, validation and the like
belongs_to :owner
belongs_to :borrower
end
基本上,组织所有者和借款人作为用户类型,继承其属性。
one_owner.products
会告诉你通过one_owner
one_borrower.products
拥有的产品将显示由one_borrower
one_product.owner
将显示该产品的拥有者借用产品
one_product.borrower
会告诉你为借款人该产品
您可以在此主题中看到一个广泛的示例:Rails Question: belongs_to with STI -- how do i do this correctly?
感谢您的回答!你能告诉我如何在这种情况下将owner_id和borrower_id连接到我的user_id吗?我必须在他们之间建立关系模型吗? – 2013-05-14 08:07:45
不,您不需要关系模型,您必须使用迁移将两列添加到您的产品模型中,并删除user_id之一,因为您不再需要它了。您将通过owner_id和借款人通过borrower_id获得所有者。 – 2013-05-14 08:26:58
你的答案和@Galen的答案之间的技术差异在哪里? – 2013-05-14 08:33:46