用于多个唯一字段的相同外键
问题描述:
RoR中的快速问题:可能有两个字段使用来自同一模型的外键吗?用于多个唯一字段的相同外键
例如,我是一名员工。我想要两个领域:我现在的商店,以及我将来会搬到的商店。在我的模型中,我怎么能有两个字段都是相同的foriegn键,但具有不同的值。
很难解释......
一个例子
EMPLOYEE TABLE
----------------------------------------------
Name Current Shop ID Next Shop ID
John Doe 2 1
SHOP TABLE
----------------------------
ID Shop Name
1 Jims Tools
2 Johns Tools
在Employee
模式,我想这两个Current Shop
和Next Shop
是从店模式外键。
答
class Employee < ActiveRecord::Base
has_one :current_shop, :class_name => Shop
has_one :next_shop, :class_name => Shop
end
class Shop < ActiveRecord::Base
belongs_to :current, :class_name => Employee
belongs_to :next, :class_name => Employee
end
答
如果外键不匹配的表名,您只需要指定它。但你可以拥有尽可能多的你想要的。
class Employee < ActiveRecord::Base
blongs_to :current_shop, :class_name => Shop, :foreign_key => "current_shop_id"
blongs_to :next_shop, :class_name => Shop, :foreign_key => "next_shop_id"
end
这里要注意的重要一点是,你必须在有外键的模型,以指定belongs_to
。如果Employee
有一个引用Shop
的密钥,那么Employee belongs to a Shop
。
就像Comment
有一个Post的外键,然后是Comment belongs to a Post
。