ActiveRecord create: pass in an array of attributes

后端 未结 2 806
野的像风
野的像风 2021-01-11 22:29

I would like to know if there is a Rails way to create multiple records by passing in an array of attributes.

For instance, instead of

MyModel.create         


        
相关标签:
2条回答
  • 2021-01-11 23:21

    At the time the question was asked ActiveRecord did not have any built-in features to efficiently insert multiple records at once. As of today Rails 6 is the current stable release and it comes with Model#insert_all! which is a method for bulk inserting.

    You'll find the documentation for it here https://edgeapi.rubyonrails.org/classes/ActiveRecord/Persistence/ClassMethods.html#method-i-insert_all-21

    It is worth to mention that Rails 6 also implements Model#upsert_all! which efficiently inserts or updates in case the the record exists.

    0 讨论(0)
  • 2021-01-11 23:27

    According the documentation you can create records from an array of hashes:

    The attributes parameter can be either be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.

     MyModel.create([{attr_1: some_attr, attr_2: 4}, {attr_1: some_attr, attr_2: 5}])
    
    0 讨论(0)
提交回复
热议问题