Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop to create multiple records in rails

I'm building an application where users can purchase tracking numbers. I have an Order model and an Order Transaction model. If the Order Transaction returns from the gateway with success, I'm using an after_save callback to trigger a method that creates the tracking numbers and inserts them into the database. Sometimes a user just orders one, but if they order more than one, I can't seem to get rails to create and insert more than one record.

Here's what I'm using -- I've never had to user a loop like this, 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
like image 858
Slick23 Avatar asked Feb 16 '26 07:02

Slick23


1 Answers

dmarkow is right that you should use trackable instead of @trackable but you also should be using = instead of ||=. You also might as well just use create. Here's how I'd write it:

 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
like image 105
klochner Avatar answered Feb 18 '26 20:02

klochner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!