I’m quite a newbie to Ruby and I need some help. I’ve got a database
table called agents that looks something like this:
create table agents {
id mediumint(8) unsigned not null,
surname varchar(60),
forename varchar(60),
manager_id mediumint(8) unsigned,
primary key(id),
constraint fk_manager(manager_id)
references agents(id)
on delete restrict
on update restrict
}
This simple table represents a sales structrue. I’ve generated the model
and I have an Agent Ruby class and added associations has_many agents
and belongs_to agent. I’ve added also a method called full_name that
just concatenates :surname and :forename.
I would now like to have the generated list view besides the surname and
forename of each agent also show the name of the manager ( manager is an
agent where id = agent.manager_id). There are some agents that don’t
have a manager aboven them.
I’ve added a method called manager_full_name to the Agent Ruby class to
avoid too much logic in the view. The code looks something like this:
def manager_full_name
manager = self.agent
manager_full_name = ‘’
manager_full_name = manager.full_name unless manager == Nil
manager_full_name
end
I use the <%= agent.manager_full_name => in my list view but it always
prints out nothing.
How can I print out the name of the manager in the view? Can I use
simple instance variable like @manager_full_name to cach the name of the
manager? I want to avoid an extra query for each time an agent is
printed out.
The ideal way is to set the @manager_full_name instance variable at
creation time (I doesn’t go with the initialize method) and set a new
value when the agent is updated.
Another thing is how to display a structure (tree) of agents with each
agent on the right level. Something like this:
A1
|
A2 A7 A4
| |
A9 A5 A7
It will quickly get ugly in the view…
Any suggestions are welkom!
Thans in advance,
Mark