views:

75

answers:

1

My data resembles this:

class Team < ActiveRecord::Base
  has_many :persons
  has_one :leader
end

class Person < ActiveRecord::Base
  belongs_to :team
end

Person only belongs to one Team, but of the many team members there is only 1 leader.

First question: should I use belongs_to instead of has_one in the Team model?

Second: Team is created with many Persons and the leader known initially. How should this be done?

Currently I am doing something like this in my controller:

  @team = Team.new

  for (each new person as p)

    new_person = @team.persons.build
    new_person.name = p.name

    if p.is_marked_as_leader
      @team.leader = new_person
    end
  end

  @team.save

This is a problem, when I list @team.persons, @team.leader has the first id, I assume because @team.save saves the leader association first. I need them to be in the order they are provided.

Thanks!

A: 

I would vote for 'has_one' for the leader, because you the person can exist outside the team and her role as team lead.

It is the aggregation vs composition discussion.

Sometimes this is open to debate, but in this case I would say the team - leader relationship is clearly composition.

Peter Tillemans
Oh, actually, the person cannot exist outside of the team and their role. The content in real use is more of a snapshot of a state of that Team in time, so the person represents the state of an external entity. Can I invert your answer to suggest that for the same reason it should in fact be belongs_to?
As I said : it is the old A vs C discussion ;-). Let me put it another way : if you delete the team, would you delete the person who is teamlead? This is a test to distinguish A from C.
Peter Tillemans
Yeah, I would delete them. Thanks :)