2

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

我的模型如下:

配置文件.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

公司.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 不返回列表呢?

4

2 回答 2

2

尝试这个:

company.reload
company.employees
于 2012-06-24T08:24:27.023 回答
0

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

于 2012-06-24T07:25:23.613 回答