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.
To illustrate the problem I just used the example code from here:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
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...
^
As you can see #{id} is not replaced with the id of the object which then raises the PostgreSQL error.
Environment
- Rails 3.1
- rvm
- PostgreSQL 9.1
- Ubuntu 11.10
- Ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]
I think what you’re actually looking for is this:
As of Rails 3.1 you have to use a proc instead of a string to use fields like
#{id}.See the issue here: https://github.com/rails/rails/issues/3920