Rails find_by_sql和id的参数

时间:2013-09-21 15:47:45

标签: mysql ruby-on-rails

快速提问,为什么第二行代码正常工作而第一行没有?

Detail.find_by_sql("SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = ?", self.id)
Detail.find_by_sql("SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = '#{self.id}'")

第一行给出了MySQL错误,看起来它没有将参数传递给SQL

Mysql2::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 details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = ?

3 个答案:

答案 0 :(得分:1)

当您使用rails语法时,find_by_sql仅支持sql查询

您应该用sql语法编写查询,如下所示:

Detail.find_by_sql("SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = #{self.id}")

或者,您也可以在rails语法中找到它:

Detail.joins(:player).where("players.team_id = ?", self.id)

答案 1 :(得分:0)

你必须像这样使用它:

Detail.find_by_sql(["SELECT * FROM details INNER JOIN players ON players.id = details.player_id WHERE players.team_id = ?", self.id])

答案 2 :(得分:0)

想对AshwinKumarS的答案发表评论,但似乎我没有代表点,所以我必须在这里发帖。他给出了正确答案,但没有解释。是的,find_by_sql仅接受单个数组作为参数。如果您查看the API doc,它会提供错误的方法签名(将sql参数显示为独立于绑定数组,但其下方的示例是正确的)。我只是浪费了,比如,一小时,试图调试由此引起的问题(当然它显示为MySQL语法错误而不是Rails错误 - 非常令人困惑和令人沮丧!)因为这种方法只接受单个,扁平数组,如果您要传递许多或可变数量的参数,请执行以下操作:

Detail.find_by_sql(["SELECT * FROM blah WHERE column1 = ? AND column2 in (?,?,?)", array_of_values].flatten)