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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.