Raw SQL when needed
📖 Scenario: You are building a simple Rails app to manage a bookstore. You have a books table with columns title, author, and price. Sometimes, you need to run raw SQL queries directly to get specific data quickly.
🎯 Goal: Learn how to write raw SQL queries in Rails using ActiveRecord::Base.connection.execute to fetch data from the books table.
📋 What You'll Learn
Create a hash representing a book with exact keys and values
Create a variable holding a raw SQL query string
Use
ActiveRecord::Base.connection.execute with the raw SQL queryAssign the query result to a variable
💡 Why This Matters
🌍 Real World
Sometimes Rails queries need to be very specific or optimized. Writing raw SQL lets you do exactly that when ActiveRecord methods are not enough.
💼 Career
Many Rails jobs require understanding how to run raw SQL safely and effectively for performance or complex queries.
Progress0 / 4 steps