我在ruby中使用迁移来与模型一起创建这些表。
我有一个表信息和一个表详细信息,信息表中的每个条目在详细信息表中都可以有一个关联。
所以我创建了它们:
create_table :details do |t|
t.integer :id
t.string :Bezeichnung
t.binary :Koordinaten
end
create_table :informations do |t|
t.integer :id
t.integer :DetailID
t.integer :Longitude
t.integer :Latitude
end
在我的信息表中,我得到了一个DetailID,它应该引用Detail表的id。
现在我做了:
ALTER TABLE informations
ADD CONSTRAINT fk_informations_details
FOREIGN KEY (DetailID)
REFERENCES details(id)
这是对的吗?我是否设置了FOREIGN KEY?或者我必须将外键放在另一个表中??
因为我想在我的信息模型中使用以下内容:
has_one :detail, :foreign_key => 'DetailID'
在详细模型中:
belongs_to :main
答案 0 :(得分:2)
一些注意事项:
detail_id
代替DetailID
如果Information has_one :detail
,Ruby on Rails将在information_id
表中查找具有匹配details
的实体。
在您的模型中,情况恰恰相反 - Information
包含detail_id
。换句话说,Ruby on Rails会将其指定为Information belongs_to :detail
和Detail has_one :information
。