DEV Community

Ren DG
Ren DG

Posted on

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
 
cescquintero profile image
Francisco Quintero πŸ‡¨πŸ‡΄

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

Collapse
 
igorkasyanchuk profile image
Igor Kasyanchuk

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