开发者

ActiveRecord relations when model has both one and many of the same model

开发者 https://www.devze.com 2023-01-07 22:05 出处:网络
My data resembles this: class Team < ActiveRecord::Base has_many :persons has_one :leader end class Person < ActiveRecord::Base

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 shou开发者_JS百科ld 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!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号