0

如果我编写自己的 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}
4

2 回答 2

1

显然,您需要proc使用 rails 3.1,如 github 问题中所述:https ://github.com/rails/rails/issues/415以及 https://stackoverflow.com/a/10620468/429850 的其他 SO答案https://stackoverflow.com/a/5465800/429850

于 2012-09-21T15:53:06.660 回答
1

尝试像这样重写它:

has_many :platform_spots, :class_name => "PlatformSpot",
            :finder_sql => proc {"select * from platform_spots where id = #{id}"}
于 2012-09-21T15:56:31.017 回答