5

so if I have an array of hashes like so: (ruby beginner)

input =  [

{"last_name"=>"Gay", "first_name"=>"Rudy", "display_name"=>"Rudy Gay", "position"=>"SF", "minutes"=>39, "points"=>25, "assists"=>6}, 
{"last_name"=>"Collison", "first_name"=>"Darren", "display_name"=>"Darren Collison", "position"=>"PG", "minutes"=>39, "points"=>14, "assists"=>4}

]

how would i iterate through the array as well as to iterate through each hash to have something like this:

player1 = {display_name=>"rudy gay", "position"=>"SF"}

player2 = {display_name=>"darren collison", "position"=>"PG"}

Would it be something like

input.each do  |x|
Player.create(name: x['display_name'], position: x['position']
end

(assuming I have a player model)

Is there a better way to achieve this?

Thanks!

meowmixplzdeliver
  • 197
  • 1
  • 3
  • 9

1 Answers1

7

Given your input:

input =  [
  { "last_name"=>"Gay", ... }, 
  { "last_name"=>"Collison", ...}
]

If all of those keys (last_name, first_name, display_name) are present in the Player model, you can just:

input.each do |x|
  Player.create(x)
end

Since create will take a hash of attributes to assign. But, even better, you don't even need to iterate:

Player.create(input)

ActiveRecord will go through them all if you give it an array of hashes.

Nick Veys
  • 23,458
  • 4
  • 47
  • 64
  • Thank you! What if I wanted to split up the hash between my Player model and my join table (Stat model) so Player.name = "darren collison" but save the points, assists, and stuff like that as Stat.assist ? (hope that made sense) I have Game, Player and Stat model, with the stat being the join table between game and player. – meowmixplzdeliver Nov 03 '14 at 22:44
  • Hard to address that in comments, and it's really a new question altogether. Give it a shot, reading [the AR associations guide](http://guides.rubyonrails.org/association_basics.html) and you'll probably get pretty close. Any other details just post again and someone will surely get you the rest of the way. – Nick Veys Nov 03 '14 at 23:11