While a loop to create multiple records in rails

I am creating an application in which users can purchase tracking numbers. I have an order model and an order transaction model. If the order transaction successfully returns from the gateway, I use the after_save callback to run the method, which creates the tracking numbers and inserts them into the database. Sometimes a user simply orders one, but if they order more than one, I cannot force the rails to create and insert more than one record.

Here is what I use - I never had to use such a loop, so I'm not sure what I'm doing wrong.

def create_trackables
      if self.success == true
        @order = Order.find(order_id)
        @start = 0
        while @start < @order.total_tokens
          @trackable_token = Tracker.create_trackable_token
          @start += 1
          @trackable ||= Tracker.new(
            :user_id => @current_user,
            :token => @trackable_token,
            :order_id => order_id
            )
        @trackable.save 
        end
      end
    end
+3
source share
2 answers

dmarkow , trackable @trackable, = ||=. create. :

 def create_trackables
    return unless self.success
    order = Order.find(order_id) #you shouldn't need this line if it has_one :order
    1.upto(order.total_tokens) do
      Tracker.create!(
                     :user_id => @current_user,
                     :token => Tracker.create_trackable_token,
                     :order_id => order_id
                     )
    end
  end
+6

@trackable trackable, . , , , @trackable , Tracker.new , @trackable.save . (Edit: ||= =).

def create_trackables
  if self.success == true
    @order = Order.find(order_id)
    @start = 0
    while @start < @order.total_tokens
      @trackable_token = Tracker.create_trackable_token
      @start += 1
      trackable = Tracker.new(
        :user_id => @current_user,
        :token => @trackable_token,
        :order_id => order_id
        )
      trackable.save 
    end
  end
end
+2

All Articles