0

How would you implement a has_n association on Rails for a given n? Let's say for example a rugby team. It has 15 players. Would you implement it as has_many and check in before save to make sure it has 15 players, or would you prefer to implement it as 15 belongs_to? Note that the order is important in this case.

Marc-André Lafortune
  • 78,216
  • 16
  • 166
  • 166
fotanus
  • 19,618
  • 13
  • 77
  • 111

2 Answers2

1

Edited to reflect your request for ordering...

You'll need to add a sort_key to the players table. You can use an integer, but a float is always a more flexible choice. Then use the :order => "sort_key" phrase.

class Team < ActiveRecord::Base
  has_many :players, :order => "sort_key", :inverse_of => :team
end

class Player < ActiveRecord::Base
  belongs_to :team, :inverse_of => :players

  validate :validate_players_count, :on => :create
  def validate_players_count
    if team.players.size > 15
      errors[:base] << "a team can only have 15 players"
    end
  end
end
Mark Paine
  • 1,874
  • 13
  • 14
0

I prefer to make it by has_many and validate players quantity when adding a new player.

I think that is the right way to make one-to-many relation.

RThomas
  • 10,702
  • 2
  • 48
  • 61