1

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?

1 Answer 1

4

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' }])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.