How to execute raw SQL in rails?

less than 1 minute read

ActiveRecord::Base.connection.execute

Make use of ActiveRecord::Base.connection.execute to execute raw SQL queries in rails.

result = ActiveRecord::Base.connection.execute("SELECT * FROM users")

ActiveRecord::Base.connection.execute with complex query

While it is totally acceptable to use the string version of SQL query.

It is advised to use the string block for clean readable query.

query = <<-SQL
  SELECT *
  FROM articles
  INNER JOIN users
          ON users.id = articles.user_id
  ORDER BY articles.created_at DESC
SQL

result = ActiveRecord::Base.connection.execute(query)

References

Tags:

Categories:

Updated: