ROR ActiveRecord attribute handling with a callback before_update

631 views Asked by At

This code produces an ActiveRecordError:

Callbacks must be a symbol denoting the method to call, a string to be evaluated, a block to be invoked, or an object responding to the callback method."

before_update :check_instock, :unless => Proc.new { |inventory| inventory.needed.nil? } 

def check_instock
  if needed < amount
    instock = true
  else
    instock = false
  end
end

This code is placed in my inventory model, I'm trying to handle some logic prior to calling @inventory.update_attributes (controller). Previously I was calling @inventory.update_attributes multiple times, which resulted in code that worked, albeit not succinctly.

Cheers!

1

There are 1 answers

0
bensie On BEST ANSWER
before_update :set_instock, :unless => :inventory_not_needed?

private

def set_instock
  self.instock = (needed < amount) ? true : false
end

def inventory_not_needed?
  needed.nil?
end