0
0
Ruby on Railsframework~20 mins

Raw SQL when needed in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Raw SQL Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this raw SQL query in Rails?
Given the following Rails code using raw SQL, what will be the output when fetching the user's name?
Ruby on Rails
user = User.find_by_sql(["SELECT name FROM users WHERE id = ?", 1]).first
user.name
A"Alice"
Bnil
C1
DActiveRecord::RecordNotFound error
Attempts:
2 left
💡 Hint
The query selects the name column for user with id 1.
📝 Syntax
intermediate
2:00remaining
Which option correctly uses raw SQL with parameter binding in Rails?
Select the option that safely executes a raw SQL query to find users older than a given age.
AUser.find_by_sql("SELECT * FROM users WHERE age > 30")
BUser.find_by_sql(["SELECT * FROM users WHERE age > ?", 30])
CUser.find_by_sql(["SELECT * FROM users WHERE age > :age", {age: 30}])
DUser.find_by_sql("SELECT * FROM users WHERE age > :age", age: 30)
Attempts:
2 left
💡 Hint
Look for the correct way to pass parameters safely to avoid SQL injection.
🔧 Debug
advanced
2:00remaining
Why does this raw SQL query raise an error in Rails?
Examine the code below and select the reason for the error raised.
Ruby on Rails
User.find_by_sql("SELECT * FROM users WHERE name = 'O'Reilly'")
ANoMethodError because find_by_sql is undefined
BActiveRecord::RecordNotFound because no user named O'Reilly exists
CSyntaxError due to unescaped single quote in SQL string
DTypeError because argument is not an array
Attempts:
2 left
💡 Hint
Look at how the single quote in the name is handled inside the SQL string.
state_output
advanced
2:00remaining
What is the value of 'count' after running this raw SQL in Rails?
Consider this code snippet. What will be the value of 'count'?
Ruby on Rails
result = ActiveRecord::Base.connection.select_all("SELECT COUNT(*) FROM users WHERE active = true")
count = result.first['count']
AAn array of all active users
BAn integer representing the number of active users
Cnil because 'count' key does not exist
DA string representing the number of active users
Attempts:
2 left
💡 Hint
Check the data type returned by raw SQL execution for count queries.
🧠 Conceptual
expert
2:00remaining
Why might you choose raw SQL over ActiveRecord query methods in Rails?
Select the best reason to use raw SQL instead of ActiveRecord query methods.
ATo perform complex queries not supported by ActiveRecord's query interface
BTo avoid learning ActiveRecord syntax
CBecause raw SQL is always faster than ActiveRecord queries
DBecause raw SQL automatically prevents SQL injection
Attempts:
2 left
💡 Hint
Think about limitations of ActiveRecord and when raw SQL is necessary.