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?
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)