我正在使用"where“语法编写一个Rails3 ActiveRecord查询,它同时使用SQL和SQL OR运算符,但不知道如何同时使用这两个运算符。
这段代码可以工作(在我的用户模型中):
Question.where(:user_id => self.friends.ids)
#note: self.friends.ids returns an array of integers
但是这段代码
Question.where(:user_id => self.friends.ids OR :target => self.friends.usernames)
返回此错误
syntax error, unexpected tCONSTANT, expecting ')'
...user_id => self.friends.ids OR :target => self.friends.usern...
你知道如何在Rails中编写这段代码,或者知道原始SQL查询应该是什么吗?
发布于 2010-11-18 03:12:11
原始SQL
SELECT *
FROM table
WHERE user_id in (LIST OF friend.ids) OR target in (LIST OF friends.usernames)
每个列表都用逗号分隔。我对Rails ActiveRecord的东西不太了解。对于AND,您只需在这两个条件之间加一个逗号,但不必使用OR
发布于 2010-11-18 03:55:43
您不需要使用原始SQL,只需将模式作为字符串提供,并添加命名参数:
Question.where('user_id in (:ids) or target in (:usernames)',
:ids => self.friends.ids, :usernames => self.friends.usernames)
或位置参数:
Question.where('user_id in (?) or target in (?)',
self.friends.ids, self.friends.usernames)
正如@ Squeel在他的回答中指出的那样,您还可以使用优秀的erroric(仅当您需要访问self
或实例变量时才需要my { }
块):
Question.where { user_id.in(my { self.friends.ids }) |
target.in(my { self.friends.usernames }) }
发布于 2011-04-18 15:06:13
尽管Rails3AR没有给你一个or运算符,但你仍然可以得到同样的结果,而不是一直到SQL,直接使用Arel。我的意思是你可以这样做:
t = Question.arel_table
Question.where(t[:user_id].in(self.friends.ids).or(t[:username].in(self.friends.usernames)))
有些人可能会说它不是很漂亮,有些人可能会说它很漂亮,因为它不包含SQL。无论如何,它肯定可以更漂亮,而且也有一个宝石: MetaWhere
欲了解更多信息,请访问以下铁路广播:http://railscasts.com/episodes/215-advanced-queries-in-rails-3和MetaWhere网站:http://metautonomo.us/projects/metawhere/
更新:后来Ryan Bates又做了一次关于metawhere和元搜索的广播:http://railscasts.com/episodes/251-metawhere-metasearch后来,尽管Metawhere (和搜索)或多或少已经成为了遗留下来的宝石。也就是说,它们甚至不能与Rails 3.1一起工作。作者认为他们(Metawhere和search)需要彻底重写。以至于他真的去买了一块新的宝石。Metawhere的后继者是Squeel。在这里阅读更多关于作者的公告:http://erniemiller.org/2011/08/31/rails-3-1-and-the-future-of-metawhere-and-metasearch/并查看项目主页:http://erniemiller.org/projects/squeel/“metasearch2.0”被称为Ransack,你可以从这里阅读到它的相关内容:http://erniemiller.org/2011/04/01/ransack-the-library-formerly-known-as-metasearch-2-0/
https://stackoverflow.com/questions/4207936
复制相似问题