0
0
Ruby on Railsframework~5 mins

Raw SQL when needed in Ruby on Rails - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is raw SQL in Rails?
Raw SQL means writing plain SQL queries directly instead of using Rails' ActiveRecord methods. It lets you run custom database commands when needed.
Click to reveal answer
beginner
Why might you use raw SQL in a Rails app?
You use raw SQL when ActiveRecord can't express a complex query easily or when you want better performance by writing optimized SQL.
Click to reveal answer
intermediate
How do you safely include user input in raw SQL queries in Rails?
Use parameter binding with question marks or named placeholders to avoid SQL injection. For example: `User.where("name = ?", user_name)`.
Click to reveal answer
intermediate
What method lets you run raw SQL directly in Rails models?
You can use `ActiveRecord::Base.connection.execute(sql)` to run raw SQL commands directly on the database.
Click to reveal answer
beginner
What is a risk of using raw SQL without care?
If you insert user input directly into raw SQL, it can cause SQL injection attacks, which let attackers access or damage your data.
Click to reveal answer
Which Rails method safely inserts user input into raw SQL queries?
AString concatenation with + operator
BUsing question marks (?) as placeholders
CDirectly inserting variables inside strings
DUsing puts to print SQL
What does `ActiveRecord::Base.connection.execute(sql)` do?
AConverts SQL to Ruby code
BCreates a new ActiveRecord model
CValidates SQL syntax only
DRuns raw SQL directly on the database
When should you prefer raw SQL over ActiveRecord methods?
AWhen queries are too complex or need optimization
BFor all simple queries
CTo avoid learning ActiveRecord
DWhen you want to write less code
What is a major security risk of careless raw SQL use?
ASlow app startup
BSyntax errors
CSQL injection attacks
DMemory leaks
Which is NOT a benefit of using raw SQL in Rails?
AEasier to write than ActiveRecord always
BMore control over queries
CBetter performance in some cases
DAbility to use database-specific features
Explain when and why you would use raw SQL in a Rails application.
Think about complex queries and security.
You got /4 concepts.
    Describe how to safely include user input in raw SQL queries in Rails.
    Focus on security best practices.
    You got /3 concepts.