我是 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\">"
我错过了什么?