views:

24

answers:

1

I'm trying to trigger a warning when a price is entered too low. But for some reason, it always returns true and I see the warning regardless. I'm sure there something wrong in the way I'm doing this as I'm really new to RoR.

In model:

def self.too_low(value)
  res = Class.find_by_sql("SELECT price ……. WHERE value = '#{value}'")
  res.each do |v|
    if #{value} < v.price.round(2)
      return true
    else
      return false
    end
  end
end

In controller:

@too_low = Class.too_low(params[:amount])
if @too_low == true
  flash[:warning] = 'Price is too low.'
end
A: 

I would write it somewhat different. You iterate over all items, but you are only interested in the first element. You return from inside the iteration block, but for each element the block will be executed. In ruby 1.9.2 this gives an error.

Also i would propose using a different class-name (Class is used to define a class)

So my suggestion:

Class YourGoodClassName

  def self.too_low(amount)
    res = YourGoodClassName.find_by_sql(...)
    if res.size > 0
      res[0].price.round(2) < 1.00
    else
      true
    end
  end

end

You can see i test if any result is found, and if it is i just return the value of the test (which is true or false); and return true if no price was found.

In the controller you write something like

flash[:warning] = 'Price is too low' if YourGoodClassName.too_low(params[:amount])  
nathanvda
nathanvda, thanks for the reply. Would you be able to explain how I would do this if I wanted to check 'amount' against two values selected from the DB?
nathanvda