DEV Community

renlstr.dev
renlstr.dev

Posted on

8 1

Executing an SQL Query Directly from ActiveRecord

You can execute sql queries directly from ActiveRecord

#execute

users = ActiveRecord::Base.connection.execute("SELECT id, first_name, created_at FROM users WHERE id=1")

users[0]
{
  "id"         => "1",
  "first_name" => "Ren",
  "created_at" => "2017-01-01 12:23:67.425118"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
igorkasyanchuk profile image
Igor Kasyanchuk β€’

more elegant solution: github.com/igorkasyanchuk/execute_sql :)

Collapse
 
cescquintero profile image
Francisco Quintero πŸ‡¨πŸ‡΄ β€’

Thanks! Very useful. In the guides this information is not present.

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging β†’

πŸ‘‹ Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s dayβ€”drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay