Ruby on Rails 3 如何制作“或"条件 [英] Ruby on Rails 3 howto make 'OR' condition
问题描述
我需要一个 SQL 语句来检查是否满足一个条件:
I need an SQL statement that check if one condition is satisfied:
SELECT * FROM my_table WHERE my_table.x=1 OR my_table.y=1
我想以Rails 3"的方式来做这件事.我正在寻找类似的东西:
I want to do this the 'Rails 3' way. I was looking for something like:
Account.where(:id => 1).or.where(:id => 2)
我知道我总是可以回退到 sql 或条件字符串.但是,根据我的经验,这在组合范围时通常会导致混乱.这样做的最佳方法是什么?
I know that I can always fallback to sql or a conditions string. However, in my experience this often leads to chaos when combining scopes. What is the best way to do this?
另一个相关问题是如何描述依赖于 OR 条件的关系.我发现的唯一方法:
Another related question, is how can describe relationship that depends on an OR condition. The only way I found:
has_many :my_thing, :class_name => "MyTable", :finder_sql => 'SELECT my_tables.* ' + 'FROM my_tables ' +
'WHERE my_tables.payer_id = #{id} OR my_tables.payee_id = #{id}'
但是,当组合使用时,它们又会中断.有没有更好的方法来指定这一点?
However, these again breaks when used in combinations. IS there a better way to specify this?
推荐答案
遗憾的是,.or 尚未实现(但一旦实现,它会很棒).
Sadly, the .or isn't implemented yet (but when it is, it'll be AWESOME).
因此您必须执行以下操作:
So you'll have to do something like:
class Project < ActiveRecord::Base
scope :sufficient_data, :conditions=>['ratio_story_completion != 0 OR ratio_differential != 0']
scope :profitable, :conditions=>['profit > 0']
那样你仍然可以很出色并做到:
That way you can still be awesome and do:
Project.sufficient_data.profitable
这篇关于Ruby on Rails 3 如何制作“或"条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!