Create child model n times in rails

Let’s say I have a User & Bonus models

class User < ActiveRecord::Base
  has_many :bonuses

class Bonus < ActiveRecord::Base
  belongs_to :user

IE I want to create n bonuses with same params for user. The simplest way is:

n.times { u.bonuses.create!(params) }

But this will trigger n transactions and can be quiet slow for browsing if n is relatively big.

How can I create all this bonuses just in one transaction through activerecord (not raw sql)?

Source: ruby

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.