Ik ben niet in staat om een of ander vreemd gedrag te achterhalen dat ik in de rials-console krijg terwijl ik wat code aan het testen ben.
Mijn modellen zijn als volgt:
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
Ik ga de railsconsole binnen
$rails c --sandbox
en test dan de volgende code
:001 > company = Company.find(2)
Company Load (4.2ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = ? LIMIT 1 [["id", 2]]
=> #
:002 > employee = Profile.find(5)
Profile Load (0.1ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."id" = ? LIMIT 1 [["id", 5]]
=> #
:003 > employee.company = company
=> #
:004 > employee.company
=> #
:005 > employee
=> #
: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
=> #
Als u de profielrecord opzoekt, wordt de company_id weergegeven, maar als u met die id naar werknemers (profielen) zoekt, wordt niets teruggezonden.
dus waarom zullen geen bedrijfsmedewerkers een lijst retourneren?