vendredi 27 octobre 2017

Dynamically passing of parameter in rails sql query

Below is an SQL query which fetches some data related to user.

def self.get_user_details(user_id)

      result = Event.execute_sql("select replace(substring_index(properties, 'text', -1),'}','') as p, count(*) as count
                  from ahoy_events e where e.user_id = ?
                  group by p order by count desc limit 5", :user_id)

      return result
 end

I want to dynamically pass values to user id to get the result. I am using the below method to sanitize sql array, but still it returns no result. The query works fine if given static parameter.

   def self.execute_sql(*sql_array)     
       connection.execute(send(:sanitize_sql_array, sql_array))
    end

Because the query is complicated I am couldn't figure out the ActiveRecord way to get the results. Is there any way I could get this sorted out?

Aucun commentaire:

Enregistrer un commentaire