ToddT ToddT - 2 months ago 14
Ruby Question

SystemStackError (stack level too deep) in Model

Unsure of why this is happening?? Still a noob..

I am just updating one field in the

Mine
table before I save the record. All of the variables are being pulled in accurately.. The below line returns what its supposed too.

CreateFulfillmentService::NON_US_MARKETPLACES.include?(self.marketplace)


And
self
is an instance of
Mine
. And
self.marketplace
returns the correct marketplace.

This is my controller

class Mine < ActiveRecord::Base
belongs_to :shop
validates :merchant_id, presence: true
validates :auth_token, presence: true
before_save :assign_three_speed

def assign_three_speed
if CreateFulfillmentService::NON_US_MARKETPLACES.include?(self.marketplace)
self.update(three_speed: false)
else
self.update(three_speed: true)
end
end

end


Where did I go astray?

Answer

before_save is a callback. It runs every time you save an instance of Mine.

In assign_three_speed, you call self.update, which ends up up calling save. That save call triggers another callback cycle, and the loop continues forever (until it quits with the SystemStackError).

Try assigning three_speed in the callback instead (instead of updating). The change will persist to the database because the assignment occurs before the model is saved.

def assign_three_speed
  if CreateFulfillmentService::NON_US_MARKETPLACES.include?(self.marketplace)
    self.three_speed = false
  else
    self.three_speed = true
  end
end