# Create multiple entities

**URL:** <https://discourse.rom-rb.org/t/create-multiple-entities/265>\
**Category:** Usage Stories\
**Created:** [July 12, 2018, 6:18am UTC](https://discourse.rom-rb.org/t/create-multiple-entities/265 "2018-07-12T06:18:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![drqCode](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.rom-rb.org/drqcode/32/160_2.png) [@drqCode](https://discourse.rom-rb.org/u/drqCode)\
**Post date:** [July 12, 2018, 6:18am UTC](https://discourse.rom-rb.org/t/create-multiple-entities/265/1 "2018-07-12T06:18:37Z")

</div>

I have this scenario when creating multiple (bulk) users with some existing tasks. The only `bulk create` implementation I have for now is to iterate through the list of new users, create a user, get his id and insert in `UsersTasks`. I expect to persist this data at most 2 database shot. Could you provide some help, please?

```ruby
class Users < ROM::Relation[:sql]
  schema(infer: true) do
    associations do
      has_many :user_tasks
      has_many :tasks, through: :user_tasks
    end
  end
end

class UserTasks < ROM::Relation[:sql]
  schema(infer: true) do
    associations do
      belongs_to :user
      belongs_to :task
    end
  end
end

class Tasks < ROM::Relation[:sql]
  schema(infer: true)
  # Note that there's no need for associations here since we won't
  # read or create tasks alongside a user or many users
end

class UserRepo < ROM::Repository::Root[:users]
  def bulk_create(new_users)
        users.transaction do
          new_users.each do |new_user|
              user = users
                 .changeset(:create, new_user)
                 .map(:add_timestamps)
                 .commit

               user_tasks
                  .changeset(:create, new_user[:tasks])
                  .associate(user, :users)
                  .commit          
           end
        end
  end
end

new_users = [
    {
        name: 'Jon Snow',
        tasks: [
            {id: 1, description: 'Burn the white walkers'},
            {id: 2, description: 'Kill Mother of Dragons'}
        ]},
    {
        name: 'Arya Stark',
        tasks: [
            {id: 3, description: 'Kill Cersei'}
        ]}
]

UserRepo.new.bulk_create(new_users)

```

---

<div class="post-metadata">

**Author:** ![ianks](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.rom-rb.org/ianks/32/145_2.png) [@ianks](https://discourse.rom-rb.org/u/ianks)\
**Post date:** [September 28, 2018, 2:59am UTC](https://discourse.rom-rb.org/t/create-multiple-entities/265/2 "2018-09-28T02:59:06Z")

</div>

Hey @drqCode, have you looked into commands at all? The `create` command accepts multiple tuples which might solve your usecase. Here is a link with more information: [https://rom-rb.org/4.0/learn/core/commands/](https://rom-rb.org/4.0/learn/core/commands/)
