Ruby-on-rails 查找两个条件为真的所有记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4953172/
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
find all records where two conditions are true
提问by sybind
I'm trying to find all records where two conditions are true. For example:
我试图找到两个条件都为真的所有记录。例如:
ruby-1.8.7-p302 > Person.all
=> #<Person name: "Jane", city: "Green Bay", state: "Wisconsin", single: true>
=> #<Person name: "Dick", city: "Madison", state: "Wisconsin", single: false>
=> #<Person name: "Tom", city: "Milwaukee", state: "Wisconsin", single: true>
I want to get the "Jane" and "Tom" records. I'm trying this, but it doesn't work:
我想获得“Jane”和“Tom”的记录。我正在尝试这个,但它不起作用:
Person.find_all_by_state("Wisconsin").find_all_by_single(true)
回答by Dylan Markow
Person.where(:state => "Wisconsin", :single => true)
Person.where(:state => "Wisconsin", :single => true)
回答by Ryan Bigg
I would go with dmarkow's answer, but as a little bit of additional trivia you can also do this:
我会同意 dmarkow 的回答,但作为一些额外的琐事,您也可以这样做:
Person.find_all_by_state_and_single("Wisconsin", true)
Chain as many fields using _and_as desired. The wheresyntax is much neater than this however.
_and_根据需要链接尽可能多的字段。然而,where语法比这简洁得多。
回答by Shivam Tripathi
Example using a OR condition:
使用 OR 条件的示例:
model_name.where("field_1 = ? OR field_2 = ?", params[:search_string], params[:search_string])

