0

I have a model with some relationship that is best described if I write my own SQL. To simplify, I write something like this (in, say MyModel.rb):

has_many :platform_spots, :finder_sql => "SELECT * FROM platform_spots WHERE id=#{id}"

in the model description.

If I now run rails console, and try to pull

MyModel.find(:first)

I get

NameError: undefined local variable or method `id' for #<Class:0x000001039e4b80>

I figure its because I need to use single quotes, so I change it to

has_many :platform_spots, :finder_sql => 'SELECT * FROM platform_spots WHERE id=#{id}'

Now, in the console

ecs = MyModel.find(:first)
ecs.platform_spots

I get the errors

  PlatformSpot Load (0.2ms)  SELECT * FROM platform_spots WHERE id=#{id}
Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1: SELECT * FROM platform_spots WHERE id=#{id}
ActiveRecord::StatementInvalid: Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1: SELECT * FROM platform_spots WHERE id=#{id}
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
  • possible duplicate of [finder\_sql does not parse string with Rails](http://stackoverflow.com/questions/8545360/finder-sql-does-not-parse-string-with-rails) – freemanoid Feb 10 '15 at 21:24

2 Answers2

1

Apparently, you need proc in rails 3.1, as given in the github issue: https://github.com/rails/rails/issues/415 and also in other SO answers at https://stackoverflow.com/a/10620468/429850 and https://stackoverflow.com/a/5465800/429850

Community
  • 1
  • 1
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
1

Try rewriting it like this:

has_many :platform_spots, :class_name => "PlatformSpot",
            :finder_sql => proc {"select * from platform_spots where id = #{id}"}
iouri
  • 2,919
  • 1
  • 14
  • 11