Src
Src

Reputation: 5502

Create associations after record creation

I need to create 4 records in table inventory after creating a user. I know that i need to use callback after_create, but i guess it is not good according to the best practices and DRY principle to have 4 lines like this:

def create_items
    Item.create({user_id: self.id, item_id: 1})
    Item.create({user_id: self.id, item_id: 2})
    ...
end

Or maybe even like that?

def create_items
    self.inventories.create([
        {item_id: 1},
        {item_id: 2}
    ])
end

Upvotes: 0

Views: 66

Answers (1)

tadman
tadman

Reputation: 211720

Ofen you can solve this with has_many :through:

class Inventory
  belongs_to :user
  belongs_to :item
end

class User
  has_many :inventories
  has_many :items, through: :inventories
end

Then you can add them straight-up:

items.each do |item|
  @user.items << item
end

If you have only ID values:

Item.where(id: ids).each do |item|
  @user.items << item
end

That's generally efficient enough to get the job done. If you're experiencing severe load problems with this you can always do it with a bulk-insert plugin, but that's usually a last-resort.

Upvotes: 5

Related Questions