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.
Asked
Active
Viewed 102 times
0

Marc-André Lafortune
- 78,216
- 16
- 166
- 166

fotanus
- 19,618
- 13
- 77
- 111
-
I think your question is directly related to this [question](http://stackoverflow.com/q/4836897/22371). – kafuchau May 15 '12 at 03:17
-
I don't think it's directly related. That question uses a join table. No need for that here. – Mark Paine May 15 '12 at 04:12
2 Answers
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
-
Then how would you change the player on the first position to the one in the forth? – fotanus May 16 '12 at 14:41
-
-
Thanks, that is what I needed. Now to change two players from positions all I have to do is update the sort key. – fotanus May 16 '12 at 19:19
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

vfedorov_ru
- 11
- 1