简体   繁体   English

如何使用Ruby on Rails进行OR SQL搜索?

[英]How do I do an OR SQL search with Ruby on Rails?

I am just beginning to learn Ruby on Rails, and I haven't been able to find the answer to this question. 我才刚刚开始学习Ruby on Rails,但还没有找到这个问题的答案。

I have the following code: 我有以下代码:

@products = Product.find(:all,
  :conditions => ["productsubtype_id = ?", @productsubtypes],
  :order => "name")

@productsubtypes is an array (currently containing two objects from another SQL query, almost identical to this one) - the SQL it generates is the following: @productsubtypes是一个数组(当前包含另一个SQL查询中的两个对象,几乎与此相同)-它生成的SQL如下:

SELECT * FROM `products` WHERE (productsubtype_id = 2,3)  ORDER BY name

As you can see, the above is not valid (at least, not for MySQL) - I need to find a way to change the original Ruby code to generate the following SQL code (or something close to it: 如您所见,以上无效(至少对于MySQL无效)-我需要找到一种方法来更改原始Ruby代码以生成以下SQL代码(或类似的代码):

SELECT * FROM `products` WHERE (productsubtype_id = 2 
  OR productsubtype_id = 3)  ORDER BY name

Is there a way to change the original code to do what I need, or am I on completely the wrong track here? 有没有一种方法可以更改原始代码以执行我需要的操作,或者我在这里完全走错了路?

Thanks for your help, 谢谢你的帮助,

Juan 胡安

These solutions both work, but ActiveRecord already has built-in support for knowing if you're passing an array or a single id when using a conditions hash. 这些解决方案都可以使用,但是ActiveRecord已经内置了对使用条件散列时是否传递数组或单个id的支持。 Example: 例:

User.all(:conditions => {:id => [1,2,3]})

generates the query 生成查询

SELECT * FROM `users` WHERE (users.`id` IN( 1,2,3 )) 

so you would want 所以你想要

@products = Product.find(:all,
  :conditions => {:productsubtype_id => @productsubtypes},
  :order => "name")

for more complex queries, though, you either need to pass sql in conditions or use a plugin (ie conditions_fu) 但是,对于更复杂的查询,您要么需要在条件中传递sql,要么使用插件(例如,conditions_fu)

Try using the conditions_fu plugin. 尝试使用conditions_fu插件。

Product.all(:conditions => { :productsubtype_id.in => @productsubtypes },
:order => "name")

@products = Product.find(:all, @products = Product.find(:all,

:conditions => ["productsubtype_id IN (?) ", @productsubtypes], :conditions => [“” productsubtype_id IN(?) “,@productsubtypes],

:order => "name") :order =>“名称”)

Also have to consider the use of IN vs EXISTS. 还必须考虑使用IN vs EXISTS。 If the subset you are using within the IN is very large, using an EXISTS might be better. 如果在IN中使用的子集非常大,则使用EXISTS可能会更好。 Basically, one uses an join, the other does not. 基本上,一个使用联接,另一个不使用联接。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM