vic*_*ich 2 ruby activerecord ruby-on-rails ruby-on-rails-3 rails-activerecord
我正在尝试添加一个条件,其中只从模型中获取满足条件的记录.例如,我试图只从Transaction模型中获取:price大于或不等于0的记录(我已尝试>和!=但在下面的示例中都没有工作).
price = Transaction.where(:company_id => company).where(:price != 0.00)
Run Code Online (Sandbox Code Playgroud)
我也试过这个:
price = Transaction.where(:company_id => company).where(:price != 0.00).collect{|item| if item.price.to_f > 0.00 {item.price.to_f} end}
Run Code Online (Sandbox Code Playgroud)
......以及上述两种不起作用的其他变体.
上面的第一个示例不会产生错误,但根本不起作用.条件被忽略了.第二个示例产生语法错误.
我也很确定有一种方法可以在SQL中使用条件,但不知道如何去做.
有什么建议?
mu *_*ort 14
这个:
.where(:price != 0.00)
Run Code Online (Sandbox Code Playgroud)
和说:
.where(true)
Run Code Online (Sandbox Code Playgroud)
作为符号永远不会等于浮点数; where(true)没有意义,因为它只是将您的数据库的真实文字('t'对于PostgreSQL,1在SQLite和MySQL中)添加到WHERE子句中,并且没有做任何有用的事情; 例如,如果你说:
Transaction.where(:company_id => company).where(:price != 0.00)
Run Code Online (Sandbox Code Playgroud)
然后你的SQL将在PostgreSQL中像这样结束:
select * from transactions where company_id = #{company} and 't'
Run Code Online (Sandbox Code Playgroud)
这就像说的一样
select * from transactions where company_id = #{company}
Run Code Online (Sandbox Code Playgroud)
当查询混乱时,有时.to_sql在Rails控制台中最后添加一个并查看SQL最终会做什么是有帮助的(如果您不了解SQL,那么如果您打算使用关系数据库,则应该学习它在任何能力).
您想将比较发送到数据库,而不是在Ruby中执行:
price = Transaction.where(:company_id => company)
.where('price != ?', 0)
Run Code Online (Sandbox Code Playgroud)
我假设你的price列是十进制类型而不是浮点类型; 如果我错了,那么现在把它改成小数.
| 归档时间: |
|
| 查看次数: |
11903 次 |
| 最近记录: |