2012-08-07 237 views
0

我在rails中有兩個模型類。外鍵關係

class EmployeeDetail < ActiveRecord::Base 
    attr_accessible :department_id 
    belongs_to :department, :class_name => "Department", :foreign_key => :department_id 
end 

class Department < ActiveRecord::Base 
    attr_accessible :name 
    validates :name, presence: true, uniqueness: { case_sensitive: false } 
end 

我要創建這兩個類之間的外鍵關係。但是當我看到employee_details表時,department_id只是一個不參考部門表的整數列。任何人都可以幫助創建外鍵關係。 thnks

回答

1

有沒有必要。 Rails爲它做了所有的工作。

您可以做的是在遷移中添加index。像:

add_index :employee_details, :department_id 
+0

遷移文件,當我運行命令耙db:遷移時,它顯示錯誤PG ::錯誤:錯誤:關係「employee_details」不存在 – 2012-08-07 11:53:15

+0

在您的部門模型中添加'has_many:employee_details' – 2012-08-07 12:35:26

0

試試這個添加到系車型:

has_many :employeedetails

也許,你並不需要

, :class_name => "Department", :foreign_key => :department_id

由於Rails加入add_index後爲你做自動