yoyo
yoyo

Reputation: 13

How can I use bulk insert in the case

how can I use bulk insert from array in Rails, like below:

name_list = [{"id" => 1,"name" => "bob"},{"id" => 2,"name" => "ted"}]

Namelist.import name_list

I can`t insert values of above array.

Upvotes: 0

Views: 53

Answers (3)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do that in single insert query using activerecord-import gem.

name_list = [{"id" => 1,"name" => "bob"},{"id" => 2,"name" => "ted"}]
namelist_objects = []
name_list.each do |n| 
  namelist_objects << Namelist.new(n)
end
Namelist.import(namelist_objects)

The above answers of others will work fine but name_list.size number of insert queries will run which is not feasible when the array is big.

Hope that helps!

Upvotes: 1

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

You can just pass the array of hash to create

Namelist.create([{id: 1, name: "bob"}, {id: 2, name: "ted"}])

Upvotes: 1

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

I am not sure what you want, but maybe it will help you. I think you want create Namelist for both name_lists, isn't ?

name_list = [{"id" => 1,"name" => "bob"},{"id" => 2,"name" => "ted"}]
name_list.map{|k| Namelist.create(k) }

Upvotes: 0

Related Questions