Search code examples
associationshas-manybelongs-toseedmodel-associations

How to properly implement an association of two models/objects via the seeds.rb in Rails?


So, here is the deal: I have two models, a Player and a Team. Every team has_many players and every player belongs_to a team. The code (omitting a few unnecessary atributes from the player model):

class Team < ActiveRecord::Base
  attr_accessible :name, :points, :rank
  has_many :players

class Player < ActiveRecord::Base
  attr_accessible :name, :age, :pos, :team
  belongs_to :team

I am using seeds.rb to create a few teams and a bunch of players and then I try to put players into teams (that is, I try to actually implement the "has_many" and "belongs_to" associations). The code:

rndm = rand(1..10) #random number of teams

rndm.each do |i| #create rndm teams
  i = i.to_s
  Team.create(name: 'Team'+i, points: 0, ranking: 0)
end

for i in 1..rndm*22 do #create rndm*22 players (ideally 22 for each team)
  i = i.to_s
  Player.create(name: 'Player'+i, age: rand(15..35), 
                pos: 'Not specified', team: Team.find(rand(1..rndm)))
end

Now, the above code creates the teams and the players just fine. However, it does not associate players with teams. It does not associate them with a team at all. That is, when I type "@player = Player.find(1)" and "@player.team" in the rails console all I get is "=> nil". BUT, when I specify the team myself (still in the console) by typing "@player.team = Team.find(1)", the association is achieved just fine (resulting in the "player.team" argument to return the details for the team with team id: 1).

I assume I have to modify the Player controller or something like that? If so, what's different when I associate the two models from the console rather than from the seeds.rb?


Solution

  • In order for you're seeding scheme to work, you'd have to be setting team_id: instead of :team when you create the Player.

    for i in 1..rndm*22 do #create rndm*22 players (ideally 22 for each team)
      i = i.to_s
      Player.create(name: 'Player'+i, age: rand(15..35), 
                pos: 'Not specified', team_id: Team.find(rand(1..rndm))).id
    end