简体   繁体   English

如何在ActiveRecord中创建“OR”语句?

[英]How can I make an 'OR' statement in ActiveRecord?

I am trying to create an 'OR' sql statement in ActiveRecord 3, I tried all kinds of variations but can't figure it out... 我试图在ActiveRecord 3中创建一个'OR'sql语句,我尝试了各种各样的变化,但无法弄清楚...

For example I want this query to include multiple 'channel_ids' and have it return all posts for any of the channel IDs. 例如,我希望此查询包含多个“channel_ids”,并让它返回任何频道ID的所有帖子。 This works for one: 这适用于一个:

Post.where(:user => 'mike').where(:channel_id => 0).limit(20)

but I cant figure out how to do it with multiples, I've tried for example: 但我无法弄清楚如何用倍数来做,我试过例如:

Post.where(:user => 'mike').where(:channel_id => ?, [0,1,2,3]).limit(20) 

but it didn't work. 但它不起作用。 How can I make this work? 我怎样才能做到这一点?

试试这个:

Post.where("posts.user = ? OR posts.channel_id IN (?)", "mike", ids)

Use the Arel methods to do this: 使用Arel方法执行此操作:

t = Post.arel_table
ids = [1,2,3]

Post.where(
  t[:user].eq("mike").or(t[:channel_id].in(ids))
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写此语句,使它保持为ActiveRecord调用? - How can I write this statement so it stays as an ActiveRecord call? 如何查看产生ActiveRecord :: StatementInvalid的SQL语句? - How can I look at the SQL statement that produced an ActiveRecord::StatementInvalid? 如何使聚合属性支持ActiveRecord :: Dirty语义? - How can I make an aggregated property support ActiveRecord::Dirty semantics? Rails / ActiveRecord - 我怎样才能使这更简洁? - Rails/ActiveRecord - How can I make this more concise? 如何打开一个类并将其转换为ActiveRecord对象? (例如,使其继承ActiveRecord :: Base) - How can I open a class and convert it into ActiveRecord object? (for example, make it inherit ActiveRecord::Base) 如果语句在这种情况下可以工作,该如何做呢? - How can I make this if statement work with this condition? 如何在不实际执行的情况下获取由ActiveRecord #ref创建的SQL语句? - How can I get SQL statement created by ActiveRecord#find without actually executing it? 如何在ActiveRecord准备好的语句中使ruby数组为ax,y,z - how to make a ruby array be a x,y,z in an ActiveRecord prepared statement 如何在 ActiveRecord 中创建一个记录数组? - How do I make a record in ActiveRecord an Array? 如何使我的ActiveRecord对象在Ruby on Rails中仅存在5分钟? - How can I make my ActiveRecord objects only exist for 5 minutes in Ruby on Rails?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM