外键关系

时间:2012-08-07 11:12:26

标签: ruby-on-rails ruby

我在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只是一个整数列而没有引用department表。任何人都可以帮助创建外键关系。 thnks

2 个答案:

答案 0 :(得分:1)

没有必要。 Rails为它做了所有的工作。

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

add_index :employee_details, :department_id

答案 1 :(得分:0)

尝试将此添加到部门模型:

  

has_many:employeedetails

也许,你不需要

  

,:class_name =&gt; “部门”,:foreign_key =&gt; :部门标识

因为Rails会为你自动执行