Ruby-on-rails 如何在 where 子句中组合两个条件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10611795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:24:31  来源:igfitidea点击:

How to combine two conditions in a where clause?

ruby-on-railsruby-on-rails-3activerecord

提问by AnApprentice

I have the following:

我有以下几点:

time_range = (1.month.ago.beginning_of_month..1.month.ago.end_of_month)

Comment.where(:created_at => time_range).count

How can I add to the where clause with a statement like:

如何使用如下语句添加到 where 子句中:

.where("user_id is not in (?)",[user_ids]).

How can I combine the two? Thanks

我怎样才能将两者结合起来?谢谢

回答by u445908

if you want a "AND" conditional query, try this:

如果你想要一个“AND”条件查询,试试这个:

Comment.
  where(:created_at => time_range).
  where("user_id is not in (?)",[user_ids])

which will produce SQL like : select ... where ... AND ...

这将产生如下 SQL: select ... where ... AND ...

if you want the WHERE clause more complicated, such as: where ( a AND b) OR (c AND d), you have to combine the conditions into the clause yourself, e.g.

如果你想让 WHERE 子句更复杂,比如: where ( a AND b) OR (c AND d),你必须自己将条件组合到子句中,例如

Comment.where("(a AND b ) OR (c AND d)")

回答by Sujith Sudersan

User.where(["name = ? and email = ?", "Joe", "[email protected]"])

This will be fine.

这会好的。

回答by shiva kumar

User.where(name: 'Joe', email: '[email protected]')