0
0
Ruby on Railsframework~30 mins

Raw SQL when needed in Ruby on Rails - Mini Project: Build & Apply

Choose your learning style9 modes available
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 query
Assign 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
1
Create a book hash
Create a hash called book with these exact key-value pairs: title: 'Eloquent Ruby', author: 'Russ Olsen', and price: 30.
Ruby on Rails
Need a hint?

Use Ruby hash syntax with keys title, author, and price.

2
Write a raw SQL query string
Create a variable called sql_query and assign it the string "SELECT * FROM books WHERE price < 40".
Ruby on Rails
Need a hint?

Assign the exact SQL string to sql_query.

3
Execute the raw SQL query
Use ActiveRecord::Base.connection.execute(sql_query) and assign the result to a variable called result.
Ruby on Rails
Need a hint?

Use ActiveRecord::Base.connection.execute with sql_query.

4
Access the first row from the result
Assign the first row of result to a variable called first_book using result.first.
Ruby on Rails
Need a hint?

Use result.first to get the first row.