0

I cant figure out how to create a relationship between a player and roster through a HABTM relationship called players_rosters, but in my console how do i create a relation between the two with attributes.

Players_rosters consists of roster_id and player_id. The relationship works but how can i create the association with manual attributes.

r = Roster.find(1)

r.create(:player_id => 1)

This doesnt work, but how could i do this?

Pierre
  • 1,114
  • 2
  • 10
  • 24

1 Answers1

4

Assuming you're finding the roster:

r = Roster.find(1)
player = r.players.create(:name => 'Joe')

Using your example of setting the player's id:

r.players.create(:id => 22, :name => 'Joe')

Find the first player and add them to the Roster with id of 22:

# Then you can assign as follows:
player = Player.first
roster = Roster.find(22)
player.rosters << roster

Or, to assign the player to only a single roster:

player = Player.first
player.rosters = [Roster.find(22)]
player.save

The save may not be necessary. I don't recall if assignment triggers a save like appending to an association.

nbrew
  • 771
  • 5
  • 6
  • Tried this but didnt work :/ player = r.players.create(:player_id => 1) i get NoMethodError for your second example :( – Pierre Nov 01 '13 at 23:55
  • You wouldn't pass the player id to create. You're actually creating a player at that point. So `r.players.create(:number => '47', :name => 'Joe Blow')`. If you wanted to set the id explicitly in create, try passing :id. `r.players.create(:id => 10, :name => 'Fred', :number => '47')`. – nbrew Nov 01 '13 at 23:59
  • r.players.create(:id => 1) creates a new player with id 1 and creates the relationship between the two, but how can i create a relationship between existing players and rosters? – Pierre Nov 02 '13 at 00:05
  • Your 4th example gives me NoMethodError: undefined method 'roster=' – Pierre Nov 02 '13 at 00:20
  • I already had has_and_belongs_to_many :rosters, tried belongs_to :roster but didn't make any difference – Pierre Nov 02 '13 at 00:29
  • See the latest update re: HABTM (which you do state in your initial q). – nbrew Nov 02 '13 at 00:33