Question

Fairly new to Ruby and I have looked around but can't really find anything on this...

I have a typical has_many-through relationship between Orders, Lineitems, and Items. I want to be able to automatically create a lineitem list containing each item in the Items table for an Order when it is saved to the database.

I am thinking a loop that will cycle through each item in the Items table and save a new Lineitem record for each would do the trick, but not quite sure how to implement it.

I know an after_save callback could be used to initialize a method once an Order is created.

Here is my thought process for a method in the Orders model...

items.each do |x|
  Lineitem.new(order_id=>@order.id,item_id=>x.id)
  Lineitem.save!
end

Any help is appreciated.

Was it helpful?

Solution

Based on this:

I want to be able to automatically create a lineitem list containing each item in the Items table for an Order when it is saved to the database.

You can use callbacks to handle this. You don't have to do loops:

class Order < ActiveRecord::Base
  before_create :add_lineitems

private
  def add_lineitems
    # This will associate all items in the items table with the new order.
    # It'll automatically add records to the lineitems table.
    self.item_ids = Item.pluck(:id)
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top