如果我编写自己的 SQL,我有一个具有某种关系的模型,这种关系可以得到最好的描述。为了简化,我写了这样的东西(在 MyModel.rb 中):
has_many :platform_spots, :finder_sql => "SELECT * FROM platform_spots WHERE id=#{id}"
在模型描述中。
如果我现在运行 rails 控制台,并尝试拉
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}