Erzu Erzu - 6 months ago 8
Ruby Question

Is it possible to put variables into my query?

I've got a postgresql query using some ActiveRecord from Ruby 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")


I want to put variables into my query like that because I don't want to use the column longitude and latitude from the database but rather some variables containing longitude and latitude values.

my_table.location = ActiveRecord::Base.connection.execute("UPDATE my_table SET location = ST_SetSRID(ST_MakePoint((?), (?), 4326)::geography"), longitude, latitude)


I can't find a way to make it work but you should understand the idea behind. Does it exist some method to use variables in my query ?

Answer

Yes you can this is a example of one of my query where i have user variable and in my sql query

 @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)
Comments