Q:

iterate over an array of hashes to create data in rails

I have an array of hashes that I am trying to seed into a database.
shoe_array = [{:department_id=>8, :follower_id=>31}, {:department_id=>9, :follower_id=>41}, {:department_id=>4, :follower_id=>49}, {:department_id=>2, :follower_id=>58}, {:department_id=>5, :follower_id=>36}, {:department_id=>9, :follower_id=>63}, {:department_id=>2, :follower_id=>52}, {:department_id=>23, :follower_id=>26}, {:department_id=>5, :follower_id=>52}, {:department_id=>6, :follower_id=>30}]

shoe_array.each do |n, k|
  department_id = n,
  follower_id = k,
  user_id = 1

  Relationship.create!(department_id: department_id,
                       follower_id: follower_id,
                       user_id: user_id)
end

I'm only getting null values for both department_id and follower_id. user_id is working.
I have tried using "#{n}" and "#{k}", to get the key values set to department and follower ids. I've also tried iterating over the array only using .each do |a| and setting department_id: a['department_id'], follower_id a['follower_id']
as seen here: iterate through array of hashes in ruby and here :How do I iterate over an array of hashes and return the values in a single string?
but I'm only still getting null values. How can I get my values into the database?

A:

shoe_array is an array of hashes, so you should iterate over each hash, and access each key-value pair:
shoe_array.each do |hash|
  department_id = hash[:department_id]
  follower_id   = hash[:follower_id]
  user_id       = 1

  Relationship.create!(
    department_id: department_id,
    follower_id:   follower_id,
    user_id:       user_id
  )
end

