是否可以将变量放入我的查询中?
我有一些使用ActiveRecord的Ruby中一个PostgreSQL查询on Rails的是否可以将变量放入我的查询中?
my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint(my_table.longitude, my_table.latitude), 4326)::geography")
我希望把变量放入我的查询一样,因为我不希望使用从数据库中列的经度和纬度,但而是一些包含经度和纬度值的变量。
my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint((?), (?), 4326)::geography"), longitude, latitude)
我找不到一种方法使其工作,但您应该了解背后的想法。它是否存在一些在我的查询中使用变量的方法?
是的,你可以,这是我的查询中的一个例子,我有使用用户变量在我的SQL查询
@from_date = Time.parse(@from).to_date.beginning_of_day
@till_date = Time.parse(@to).to_date.end_of_day
sql = "select abc.sss,im.lat,
im.long from users as rq JOIN images as
im ON rq.id= im.imageable_id where rq.created_at
BETWEEN '#{@from_date}' AND '#{@till_date}' ;"
response = ActiveRecord::Base.connection.execute(sql)
您是否使用相同如下建议的东西? – Erzu
你知道如何在你的SQL查询中使用变量吗?我已经向你展示了我的一个例子 –
'#{longitude}'如果它不起作用,你可以使用它,然后使用#{longitude} –
告诉我没有工作? –
[如何在rails中使用动态绑定执行原始更新sql]可能的重复(http://stackoverflow.com/questions/4483049/how-to-execute-a-raw-update-sql-with-dynamic-binding -in-rails) – max
好吧,它的工作部分,当我的经度和纬度值为零它显示此错误:'错误:类型双精度无效输入语法:“”(ActiveRecord :: StatementInvalid)' – Erzu