Matt
Matt

Reputation: 14038

Add one child item to many parent items

I have owners that have many notes. I want to efficiently add the same new note to many owners as individual records so I can alter it for each owner later without affecting the other owners.

The owners I need to add the note to are known only as a list of IDs at this point (selected from a multi select list).

Is there any way more efficient than the following?

owner_ids = [1,2,3,4]
note = Note.new(params[:note])
owner_ids.each do |owner_id|
  Owner.find(owner_id).notes << note
end

OR

owner_ids = [1,2,3,4]
owner_ids.each do |owner_id|
  Note.create(owner_id: owner_id, subject: params[:note][:subject], content: params[:note][:content])
end

Using Ruby 2 with Rails 4

Upvotes: 0

Views: 99

Answers (2)

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

You can use ActiveRecord transaction method, which will execute SQL in one transaction. This can save your some time

ActiveRecord::Base.transaction do 
  owner_ids.each do |owner_id|
    Note.create(owner_id: owner_id, subject: params[:note][:subject], content: params[:note][:content])
  end
end

Also take a look at activerecord-import gem, maybe it will suit your needs better.

Upvotes: 1

Alex Teut
Alex Teut

Reputation: 844

owner_ids = [1,2,3,4]
owner_ids.each do |owner_id|
  Note.create(params[:note].merge({owner_id: owner_id}))
end

UPD: wrap all creations in a transaction is a good idea too.

Upvotes: 1

Related Questions