使用foreign_key选项的has_many关联似乎不起作用?

时间:2013-08-18 22:24:01

标签: ruby-on-rails associations has-many

我是Rails的新手,我遇到了使用“不同”主/外键命名约定而不是Rails支持的模型的问题。 (好吧,我认为这可能是问题所在)

所以这些是我的两个模型:

class Project < ActiveRecord::Base
   self.primary_key = "PROJECT_ID"
   has_many :employees, :foreign_key => "PROJECT_ID"
end

class Employee < ActiveRecord::Base
   self.primary_key = "EMPLOYEE_ID"
   belongs_to :project, :primary_key => "PROJECT_ID"
end

这就是让我疯狂的原因:

> p = Project.find(2)
  Project Load (0.2ms)  SELECT "projects".* FROM "projects" WHERE "projects"."PROJECT_ID" = ? LIMIT 1  [[nil, 2]]
 => #<Project project_id: 2, name: "Project 2", created_at: "2013-08-18 21:26:33.538007", updated_at: "2013-08-18 21:26:33.538007"> 

> p.employees.inspect
  Employee Load (0.2ms)  SELECT "employees".* FROM "employees" WHERE "employees"."PROJECT_ID" = ?  **[[nil, nil]]**
 => "#<ActiveRecord::Associations::CollectionProxy []>"

由于某种原因,我没有收到带有project_id = 2的员工。似乎是?被nil取代。

反之亦然,请查看

> e = Employee.find_by_project_id(2)
  Employee Load (0.2ms)  SELECT "employees".* FROM "employees" WHERE "employees"."project_id" = 2 LIMIT 1
 => #<Employee employee_id: 2, first_name: "Will", last_name: "Smith", project_id: 2, created_at: "2013-08-18 21:21:47.884919", updated_at: "2013-08-18 21:22:48.263970"> 

> e.project.inspect
  Project Load (0.2ms)  SELECT "projects".* FROM "projects" WHERE "projects"."PROJECT_ID" = ? ORDER BY "projects"."PROJECT_ID" ASC LIMIT 1  [[nil, 2]]
 => "#<Project project_id: 2, name: \"Project 2\", created_at: \"2013-08-18 21:26:33.538007\", updated_at: \"2013-08-18 21:26:33.538007\">"

我错过了什么?

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

class Project < ActiveRecord::Base
   self.primary_key = "PROJECT_ID"
   has_many :employees, :foreign_key => "PROJECT_ID", :primary_key => "PROJECT_ID"
end

class Employee < ActiveRecord::Base
   self.primary_key = "EMPLOYEE_ID"
   belongs_to :project, :primary_key => "PROJECT_ID", :foreign_key => "PROJECT_ID"
end

如果您使用大写字段名称(我不确定根据您的问题),请确保始终使用大写字母名称(例如find_by_PROJECT_ID)。 Rails和ActiveRecord区分大小写。

答案 1 :(得分:0)

试试这个:

class Project < ActiveRecord::Base
  self.primary_key = "PROJECT_ID"
  has_many :employees
end

class Employee < ActiveRecord::Base
  attr_accessible :project
  self.primary_key = "EMPLOYEE_ID"
  belongs_to :project
end

尽量避免使用大写列名称。

此处的记录为schema.rb

  create_table "employees", :primary_key => "EMPLOYEE_ID", :force => true do |t|
    t.integer  "project_id"
  end

  create_table "projects", :primary_key => "PROJECT_ID", :force => true do |t|
  end