简体   繁体   中英

How to create many records in join table in one query in Rails?

class Item
  has_many :list_items, :dependent => :destroy

class List
  has_many :list_items, :dependent => :destroy

I have 2 has_many relationships with a join table ( lists_items ). When adding many items to the list,

list << items

a sql query is executed for each item:

INSERT INTO "list_items" ("item_id", "list_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" ...

Is there a way to insert many records with a single query?

Is there a special reason this is not provided by Rails, like callbacks?

Rails 6.

If you are using Rails 6.1+, you could use:

list.list_items.insert_all(
  [
    {
      attribute1: 'value1',
      attribute2: 'value2'
    },
    {
      attribute1: 'value3',
      attribute2: 'value4'
    },
  ]
)

But be aware that the solution above will skip validations and callbacks.

If you want a bulk inserting solution that also handles callbacks and validations, take a look at activerecord-import gem.

As @felipeecst mentioned, activerecord-import gem is a good solution:

items_to_add = ...
list = ...

new_list_items = items_to_add.map do |i|
  ListItem.new(item: i, list: list)
end

UserSpiritListItem.import! new_list_items

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM