Rails has_many外键生成空数组

时间:2012-06-24 07:13:00

标签: ruby-on-rails activerecord foreign-keys has-many

在我测试一些代码时,我无法弄清楚我在rials控制台中遇到的一些奇怪的行为。

我的模型如下:

profile.rb

class Profile < ActiveRecord::Base
  belongs_to :user
  belongs_to :company

  attr_accessible :first_name, :last_name


  validates :first_name, presence: true
  validates :last_name, presence: true

end

company.rb

class Company < ActiveRecord::Base

  has_many :employees, :foreign_key => 'company_id', :class_name => "Profile"
  attr_accessible :name
  validates :name,  presence: true, length: { maximum: 50 }, uniqueness: true

end

我进入rails控制台

$rails c --sandbox

然后测试以下代码

:001 > company = Company.find(2)
Company Load (4.2ms)  SELECT "companies".* FROM "companies" WHERE "companies"."id" = ?     LIMIT 1  [["id", 2]]
 => #<Company id: 2, name: "Jet Star", created_at: "2012-06-24 04:12:50", updated_at:  "2012-06-24 04:12:50"> 
:002 > employee = Profile.find(5)
Profile Load (0.1ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" = ? LIMIT 1  [["id", 5]]
=> #<Profile id: 5, user_id: 5, first_name: "Douglas", last_name: "Reed", created_at: "2012-06-17 15:05:58", updated_at: "2012-06-17 15:05:58", deleted: false, company_id: nil> 
:003 > employee.company = company
=> #<Company id: 2, name: "Jet Star", created_at: "2012-06-24 04:12:50", updated_at: "2012-06-24 04:12:50"> 
:004 > employee.company
=> #<Company id: 2, name: "Jet Star", created_at: "2012-06-24 04:12:50", updated_at: "2012-06-24 04:12:50"> 
:005 > employee
=> #<Profile id: 5, user_id: 5, first_name: "Douglas", last_name: "Reed", created_at:  "2012-06-17 15:05:58", updated_at: "2012-06-17 15:05:58", deleted: false, company_id: 2> 
:006 > company.employees
Profile Load (0.2ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."company_id" = 2
=> [] 
:007 > Profile.find_by_company_id(2)
Profile Load (0.2ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."company_id" = 2 LIMIT 1
 => nil 
:008 > employee.save
(0.1ms)  SAVEPOINT active_record_1
(0.4ms)  UPDATE "profiles" SET "company_id" = 2, "updated_at" = '2012-06-24 07:35:14.525138' WHERE "profiles"."id" = 5
(0.0ms)  RELEASE SAVEPOINT active_record_1
=> true 
:009 > company.employees
=> []  
:010 > Profile.find_by_company_id(2)
  Profile Load (0.2ms)  SELECT "profiles".* FROM "profiles" WHERE "profiles"."company_id" = 2 LIMIT 1
=> #<Profile id: 5, user_id: 5, first_name: "Douglas", last_name: "Reed", created_at: "2012-06-17 15:05:58", updated_at: "2012-06-24 07:35:14", deleted: false, company_id: 2> 

如果您查看个人资料记录,它会显示company_id,但是当您搜索具有该ID的员工(个人资料)时,不会返回任何内容。

那么为什么company.employees不会返回列表?

2 个答案:

答案 0 :(得分:2)

试试这个:

company.reload
company.employees

答案 1 :(得分:0)

编写'employee.company = company'只会将员工的公司ID设置在内存中。当您查询company.employee时,它会搜索employee表(在磁盘上)但在那里找不到id,因为尚未提交更改。