Richlewis
Richlewis

Reputation: 15374

Using Rails console to insert an array of data

If I want to insert a record into my model I usually do something like this within the Rails console:

m = ModelName.create(name: 'This is my name')
m.save

But if I have an array

['Name 1', 'Name 2', 'Name 3' ]

How can I create a record for each of the items in the array using the Rails console?

Upvotes: 1

Views: 2341

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can do as below :

records_to_create = ['Name 1', 'Name 2', 'Name 3' ].map { |val| {:name => val } }
ModelName.create records_to_create

#create documentation is clear on this :-

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

Doco has some examples too :-

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

Upvotes: 4

Related Questions