简体   繁体   English

Ruby on Rails / MySQL:如何使用OR在数组上进行搜索?

[英]Ruby on Rails / MySQL: how do I do a search on an array using OR?

Both privacy and users are arrays. 隐私和用户都是数组。 I've taken out some logic to show the important stuff. 我已经抽出一些逻辑来展示重要的东西。

  named_scope :non_employees_and_beloning_to_users, lambda { |args|
    privacy = args[0]
    users = args[1]
    { :conditions =>  ["(visibility = ? && user_id = ?)", privacy, users] }
  }

but basically, the above generates the below, and when typed into a MySQL editor thing, no results show up. 但基本上,上面的内容生成了下面的内容,当将其键入到MySQL编辑器中时,不会显示任何结果。 so, I came to believe this isn't the correct method for searching for stuff in mySOL with an array? 因此,我开始相信这不是在mySOL中使用数组搜索内容的正确方法吗?

SELECT * 
FROM `proposals`  
WHERE visibility = '1,0' && user_id = '-1,8,9,11';

I want it to have the effect of 我希望它具有以下效果

visibility = (1 or 0 ) AND user_id = (-1 or 8 or 9 or 11)

Since it seems that you have a comma separated list of values in visibility and users you could use MySQL's IN() function. 由于似乎可见性和用户中用逗号分隔的值列表,可以使用MySQL的IN()函数。 Something like: 就像是:

visibility IN (1,0) AND user_id IN (-1,8,9,11)

(see here for more info on IN(): http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in ) (有关IN()的更多信息,请参见此处: http : //dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in

Alternatively you could convert visibility and users to Ruby arrays and then generate similar SQL code manually. 或者,您可以将可见性和用户转换为Ruby数组,然后手动生成类似的SQL代码。

If args[0] and args[1] are arrays of ids, you just do this: 如果args[0]args[1]是ID数组,则只需执行以下操作:

named_scope :non_employees_and_belonging_to_users, lambda { |args|
  privacy = args[0]
  users = args[1]
  { :conditions =>  ["visibility IN (?) AND user_id IN (?)", privacy, users] }
}

You need to wrap your ? 您需要包装? placeholders in parens for SQL's IN to work. 占位符中的占位符,以使SQL的IN起作用。 This should generate: 这将生成:

SELECT * FROM `proposals` WHERE visibility IN (1,0) AND user_id IN (-1,8,9,11);

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

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