1

我是 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\">"

我错过了什么?

4

2 回答 2

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 区分大小写。

于 2013-08-18T23:04:08.253 回答
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
于 2013-08-19T09:20:44.670 回答