我有一个关系模型,如果我编写自己的SQL,最好描述一下。为了简化,我写了这样的东西(在MyModel.rb中):
has_many :platform_spots, :finder_sql => "SELECT * FROM platform_spots WHERE id=#{id}"
在模型描述中。
如果我现在运行rails console,并尝试拉
MyModel.find(:first)
我得到了
NameError: undefined local variable or method `id' for #<Class:0x000001039e4b80>
我认为它是因为我需要使用单引号,因此我将其更改为
has_many :platform_spots, :finder_sql => 'SELECT * FROM platform_spots WHERE id=#{id}'
现在,在控制台中
ecs = MyModel.find(:first)
ecs.platform_spots
我收到了错误
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}
答案 0 :(得分:1)
显然,您需要导轨3.1中的proc
,如github问题中所述:https://github.com/rails/rails/issues/415以及https://stackoverflow.com/a/10620468/429850和https://stackoverflow.com/a/5465800/429850
答案 1 :(得分:1)
尝试重写它:
has_many :platform_spots, :class_name => "PlatformSpot",
:finder_sql => proc {"select * from platform_spots where id = #{id}"}