Reputation: 13
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
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
Reputation: 23711
You can just pass the array of hash to create
Namelist.create([{id: 1, name: "bob"}, {id: 2, name: "ted"}])
Upvotes: 1
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