In Ruby on Rails how to insert several records at once with ActiveRecord

-1

I want to do this as if I were doing it in mysql

INSERT INTO ratings
('id','app_id','user_id','created_at','updated_at','unique','valoracion','valoracions_id') 
values (1,2,3,"2017-04-07","2017-04-07",12,4.8,1),
       (1,2,3,"2017-04-07","2017-04-07",12,4.8,1),
       (1,2,3,"2017-04-07","2017-04-07",12,4.8,1);
    
asked by Brayan Jimenez 07.04.2017 в 17:18
source

2 answers

2

You can create several objects with the% create by passing a hash array, where each hash describes the attributes of the object you want to create.

The following example is found in the apidock :

# Create an Array of new objects
User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])

Therefore for your case it should be something like this:

Rating.create([
{app_id: 1, unique: 12, valoracion: 4.8, valoracions_id: 1},
{app_id: 2, unique: 12, valoracion: 4.8, valoracions_id: 1},
{app_id: 3, unique: 12, valoracion: 4.8, valoracions_id: 1}
])
    
answered by 07.04.2017 в 20:30
1

You can also iterate over each of them using each and using the values of each key on the array of hashes.

[
  { app_id: 2, user_id: 3, created_at: '2017-04-07', updated_at: '2017-04-07', unique: 12, valoracion: 4.8, valoracions_id: 1 }, 
  { app_id: 2, user_id: 3, created_at: '2017-04-07', updated_at: '2017-04-07', unique: 12, valoracion: 4.8, valoracions_id: 1 }, 
  { app_id: 2, user_id: 3, created_at: '2017-04-07', updated_at: '2017-04-07', unique: 12, valoracion: 4.8, valoracions_id: 1 }
].each do |rating|
  Rating.create(
    app_id:         rating[:app_id],
    user_id:        rating[:user_id],
    created_at:     rating[:created_at],
    updated_at:     rating[:updated_at],
    unique:         rating[:unique],
    valoracion:     rating[:valoracion],
    valoracions_id: rating[:valoracions_id]
  )
end

And if you want to gain some time you can use Active Record Transactions in the case of make many records.

ActiveRecord::Base.transaction do
  ...
end
    
answered by 07.04.2017 в 21:30