Ruby on rails Rails-触发闪光警告,方法返回true

Ruby on rails Rails-触发闪光警告,方法返回true,ruby-on-rails,Ruby On Rails,当输入的价格过低时,我试图触发警告。但出于某种原因,它总是返回真值,我看到了警告。我确信我做这件事的方式有点不对劲,因为我对RoR真的很陌生 在模型中: 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

当输入的价格过低时,我试图触发警告。但出于某种原因,它总是返回真值,我看到了警告。我确信我做这件事的方式有点不对劲,因为我对RoR真的很陌生

在模型中:

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

我会写一些不同的东西。您迭代所有项目,但只对第一个元素感兴趣。您可以从迭代块内部返回,但对于每个元素,都将执行该块。在ruby 1.9.2中,这会给出一个错误

我还建议使用不同的类名(
class
用于定义类)

因此,我的建议是:

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

结果集是否包含多行?如果是这样,您可能会基于最后一行的值返回
true
,因为
每个
块都将对集合中的所有行执行。我忘了提到结果集只包含一行。您能解释一下sql查询的结果吗?查询的结果应该是1.00nathanvda,谢谢您的回复。如果我想根据从数据库中选择的两个值检查“金额”,您能否解释我将如何执行此操作?然后您是否需要执行两个查询,并执行类似于
result\u from_query1[0]。price.round(2)<1.00&&result\u from_query2[0]。price>135
。像这样的?我不太明白你的意思。
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
flash[:warning] = 'Price is too low' if YourGoodClassName.too_low(params[:amount])