2

コードをテストしているときにリアルコンソールに表示される奇妙な動作を理解できません。

私のモデルは次のとおりです。

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でemployees(profiles)を検索しても、何も返されません。

では、なぜ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 に答える