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

时间:2010-08-06 20:28:40

标签: mysql ruby-on-rails

隐私和用户都是数组。 我已经拿出一些逻辑来展示重要的东西。

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

但基本上,上面生成了以下内容,当输入MySQL编辑器时,没有显示结果。所以,我开始相信这不是用数组搜索mySOL中的东西的正确方法吗?

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

我希望它具有

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

2 个答案:

答案 0 :(得分:1)

由于您可以在可见性和用户中使用逗号分隔的值列表,因此您可以使用MySQL的IN()函数。类似的东西:

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

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

或者,您可以将可见性和用户转换为Ruby数组,然后手动生成类似的SQL代码。

答案 1 :(得分:0)

如果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] }
}

您需要将?占位符包装在SQL IN的parens中。这应该产生:

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