2012-06-24 48 views
2

我無法弄清一些奇怪的行爲,即時進入里亞爾控制檯,而我測試了一些代碼。Rails has_many外鍵產生空陣列

我的型號如下:

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 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

試試這個:

company.reload 
company.employees 
+0

中我是否需要這樣做我的控制器,或者這是隻需要在控制檯? –

+0

如果所有相同的代碼都在一個控制器中,那麼是的,您必須重新加載公司實例,以便從數據庫中獲得正確的信息。 – lee

0

寫'employee.company = company'只設置員工在公司內存中的公司ID。當您查詢company.employee時,它會搜索僱員表(在磁盤上),但在那裏找不到id,因爲尚未提交更改。

+0

我已經更新了問題的細節。正如你所看到的,我保存了記錄,但即使在我試圖訪問員工列表時,該數組仍然是空的 –

+0

公司如何定義「員工」? – cdesrosiers

+0

在has_many關係中,因爲我更有意義地說一家公司有很多員工,但實際記錄存儲在配置文件表 –