Rails更多陈述;不起作用......:s

时间:2010-04-03 15:05:59

标签: sql mysql ruby-on-rails

我有这个代码,但我无法使其工作:

images = Image.find_by_sql('PREPARE stmt FROM \' SELECT * FROM images AS i WHERE i.on_id = 1 AND i.on_type = "profile" ORDER BY i.updated_at LIMIT ?, 6\'; SET @lower_limit := ((5 DIV 6) * 6);  EXECUTE stmt USING @lower_limit;')

我收到了这个错误:

Mysql ::错误:您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以便在'SET @lower_limit:=((5 DIV 6)* 6)附近使用正确的语法;执行stmt USING @lower_limit'在第1行:PREPARE stmt FROM'SELECT * FROM images AS i WHERE i.on_id = 1 AND i.on_type =“profile”ORDER BY i.updated_at LIMIT?,6'; SET @lower_limit:=((5 DIV 6)* 6);执行stmt USING @lower_limit;

但如果我使用sql app,就像这样,它可以工作:

PREPARE stmt FROM ' SELECT * FROM images AS i WHERE i.on_id = 1 AND i.on_type = "profile" ORDER BY i.updated_at LIMIT ?, 6'; SET @lower_limit := ((5 DIV 6) * 6);  EXECUTE stmt USING @lower_limit;

解决: 这会生成2个查询,更糟糕,但现在我可以获得图像的偏移量。 反过来只有一个查询,但我不会得到图像的任何偏移,无论如何我无法使它工作。

def self.get_image_offset(id)
    image_offset = Image.find_by_sql("SELECT COUNT(id) as pos FROM images WHERE updated_at <= (SELECT updated_at FROM images WHERE id = #{id})")[0].pos.to_i
  end

  def self.get_group_offset(id, per_block, image_offset = nil)
    image_offset ||= Image.get_image_offset(id)
    group_offset = (image_offset / per_block).floor * per_block
    {:image_offset => image_offset, :group_offset => group_offset, :group_number => ( group_offset + per_block ) / per_block}
  end

1 个答案:

答案 0 :(得分:1)

如果你自己编写整个sql(这不是'Rails方式',但这完全是另一个故事),你最好使用execute [1]之类的东西。

[1] http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#M001934