accessing previous methods in a chain (Ruby (on Rails))
Lets say I have classes for employees, managers, and companies. These inherit from ActiveRecord
and are all associated as you might expect.
I have two instances of the 开发者_运维技巧Employee
class, bob
and jane
. They both work for the same company but have different managers.
I want to be able to call bob.company.x
or jane.company.x
and get different results because, although they work for the same company, they have different managers. There are other limitations that prevent me from just defining x as a method for employees and calling bob.company_x
, which I realize would be simpler in this example.
Is there any way that I can know, within my method definition for x, which employee started this method chain?
What you propose cannot be done in a clean and simple way, and aside of that, is counter-intuitive.
class Employee
belongs_to :company
belongs_to :manager
end
is the only clean solution. This has the relations cleanly defined. These relations need to be available anyway: how would you know which is the manager for bob
?
A solution, as you propose, where you can write bob.company.my_manager
does not make sense, because bob.company
is his company, and at that level (Company
) there is no more knowledge of bob
.
For completeness sake: actually a manager is an employee itself, so we would write that relation a bit differently:
class Employee
belongs_to :manager, :class => Employee
end
(and in your employees
table you need to add a field manager_id
).
Hope this helps.
精彩评论