在Ruby on Rails中设置关联

时间:2012-11-03 13:42:41

标签: mysql ruby-on-rails activerecord

我在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

1 个答案:

答案 0 :(得分:2)

一些注意事项:

  1. 使用迁移对数据库执行各种更改,不要手动执行。
  2. 尽可能使用Ruby on Rails命名约定。这意味着使用detail_id代替DetailID
  3. 您的关联错误。
  4. 如果Information has_one :detail,Ruby on Rails将在information_id表中查找具有匹配details的实体。

    在您的模型中,情况恰恰相反 - Information包含detail_id。换句话说,Ruby on Rails会将其指定为Information belongs_to :detailDetail has_one :information