finder_sql不解析字符串使用Rails [英] finder_sql does not parse string with Rails
问题描述
我有一个查询我使用的问题 finder_sql
不正确地分析它交给了前向PostgreSQL导致数据库语法错误。
I have the problem that the query I use for finder_sql
is not parsed correctly before it is handed over to PostgreSQL resulting in a database syntax error.
为了说明我刚才用的例子code从这里的问题:
To illustrate the problem I just used the example code from here:
的http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
我只改将class_name
到用户
,因为我没有一个人的模型,但是这并不事情在这里。
I only changed class_name
to "User"
as I don't have a person model but this does not matter here.
has_many :subscribers, :class_name => "User", :finder_sql =>
'SELECT DISTINCT people.* ' +
'FROM people p, post_subscriptions ps ' +
'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
'ORDER BY p.first_name'
当我用这个,我得到以下错误:
When I use this, I get the following error:
User Load (0.3ms) SELECT DISTINCT people.* FROM people p, post_subscriptions ps WHERE
ps.post_id = #{id} AND ps.person_id = p.id ORDER BY p.first_name
PGError: ERROR: Syntaxerror near »{«
LINE 1: ...ople p, post_subscriptions ps WHERE ps.post_id = #{id} AND p...
^
正如你可以看到#{ID}
不与随后引发的PostgreSQL错误的对象的ID代替。
As you can see #{id}
is not replaced with the id of the object which then raises the PostgreSQL error.
环保
- 的Rails 3.1
- RVM
- 的PostgreSQL 9.1
- 的Ubuntu 11.10
- 红宝石1.9.2p290(2011-07-09改版32553)的x86_64-linux的]
推荐答案
我想你实际上是在寻找的是这样的:
I think what you're actually looking for is this:
has_many :posts, :finder_sql =>
proc {"SELECT p.* from posts p join topics t on p.topic_id = t.id where t.id=#{id}"}
由于Rails的3.1,你必须使用一个字符串的一个进程,而不是使用像田#{ID}
。
请参阅这里的问题: https://github.com/rails/rails/issues/3920
这篇关于finder_sql不解析字符串使用Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!