我需要一条SQL语句来检查是否满足一个条件:
SELECT * FROM my_table WHERE my_table.x=1 OR my_table.y=1
我想用“Rails 3”的方式来做这件事。我在找类似这样的东西:
Account.where(:id => 1).or.where(:id => 2)
我知道我总是可以退回到sql或条件字符串。然而,根据我的经验,在组合作用域时,这经常会导致混乱。做这件事最好的方法是什么?
另一个相关的问题是,如何描述依赖于OR条件的关系。我发现的唯一方法是:
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}'
然而,当它们在组合中使用时,它们再次中断。有没有更好的方式来指定这一点?
发布于 2010-07-20 23:43:16
遗憾的是,.or还没有实现(但当它实现的时候,它将是非常棒的)。
所以你必须这样做:
class Project < ActiveRecord::Base
scope :sufficient_data, :conditions=>['ratio_story_completion != 0 OR ratio_differential != 0']
scope :profitable, :conditions=>['profit > 0']
这样一来,你仍然可以变得很棒,并做到:
Project.sufficient_data.profitable
发布于 2012-12-10 19:02:56
Account.where(id: [1,2])
不需要解释。
发布于 2011-04-30 01:33:12
这将在Rails 5中工作,请参阅rails master:
Post.where('id = 1').or(Post.where('id = 2'))
# => SELECT * FROM posts WHERE (id = 1) OR (id = 2)
对于Rails 3.0.4+:
accounts = Account.arel_table
Account.where(accounts[:id].eq(1).or(accounts[:id].eq(2)))
https://stackoverflow.com/questions/3291152
复制相似问题