在rails中使用字符串变量进行数据库查询

时间:2014-12-16 20:12:28

标签: ruby-on-rails ruby-on-rails-4

我正在尝试创建一个字符串并在我的数据库查询中使用它。这段代码不起作用:

<% $cat_str = "'cat_id= ? OR cat_id=? OR cat_id=? ', '14', '15', '25'" %>   
<% @afilliate = Afilliates.find(Categories.where($cat_str).order('created_at DESC').last.af_id %>

但是,此代码有效:

 <% @afilliate = Afilliates.find(Categories.where('cat_id= ? OR cat_id=? OR cat_id=? ', '14', '15', '25').order('created_at DESC').last.af_id )%>

关于这一点的奇怪之处在于我在第一个代码块中打印生成的字符串,并且它打印出我在第二个查询中使用的字符串,该字符串有效。有任何想法吗?谢谢。

2 个答案:

答案 0 :(得分:0)

在你的第二个例子中,你有两个字符串

'cat_id= ? OR cat_id=? OR cat_id=? '

'14', '15', '25'

在您的第一个示例中,您只有一个字符串,where无法理解。

如果有办法让您的代码执行此操作,最好运行Category.where(cat_id: [14, 15, 25]),即cat_ids = [14, 15, 25)然后Category.where(cat_id: cat_ids)

作为旁注,将$放在ruby变量名前面有一个特殊的含义(它是一个全局变量),在这种情况下我不会想到它。

答案 1 :(得分:0)

之前的评论给了我很多帮助,我非常感谢那个救了我一天的人:-)

实际上有效的是:

 <% $cat_str = "14, 15, 25" %>
<% @afilliate = Afilliates.find(Categories.where(cat_id: [$cat_str]).order('created_at ASC').offset(2).last.af_id ) %>