0
0
Ruby on Railsframework~10 mins

Raw SQL when needed in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to execute a raw SQL query using ActiveRecord.

Ruby on Rails
User.find_by_sql("SELECT * FROM users WHERE id = [1]")
Drag options to blanks, or click blank then click option'
A1
Bid
Cuser_id
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using a column name instead of a value.
Using a string without quotes in SQL.
2fill in blank
medium

Complete the code to safely insert a variable into a raw SQL query using ActiveRecord.

Ruby on Rails
User.find_by_sql(["SELECT * FROM users WHERE email = ?", [1]])
Drag options to blanks, or click blank then click option'
Auser_email
Bemail
C:email
D"user@example.com"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a symbol or variable name instead of a string.
Not quoting the email string.
3fill in blank
hard

Fix the error in the raw SQL query that fetches users with age greater than 30.

Ruby on Rails
User.find_by_sql("SELECT * FROM users WHERE age [1] 30")
Drag options to blanks, or click blank then click option'
A=
B>
C<
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' which selects only age 30.
Using '<' which selects younger users.
4fill in blank
hard

Fill both blanks to write a raw SQL query that selects users with name starting with 'A' and orders by created_at descending.

Ruby on Rails
User.find_by_sql("SELECT * FROM users WHERE name [1] 'A%' ORDER BY created_at [2]")
Drag options to blanks, or click blank then click option'
ALIKE
BASC
CDESC
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '=' instead of 'LIKE' for pattern matching.
Ordering ascending instead of descending.
5fill in blank
hard

Fill all three blanks to write a raw SQL query that updates the user's email where id matches, using parameterized query.

Ruby on Rails
User.connection.execute(ActiveRecord::Base.send(:sanitize_sql_array, ["UPDATE users SET email = [1] WHERE id = [2]", [3]]))
Drag options to blanks, or click blank then click option'
A"new_email@example.com"
Buser_id
D42
Attempts:
3 left
💡 Hint
Common Mistakes
Using unquoted strings for email.
Using variable names instead of actual values.