Hint: Use order then limit with correct method names [OK]
Common Mistakes:
Using non-existent methods like order_by or sort
Swapping method names incorrectly
Incorrect chaining order causing errors
3. Given the code Product.order(price: :desc).limit(3).pluck(:price), what will be the output if prices are [10, 50, 30, 20, 40]?
medium
A. [10, 20, 30]
B. [40, 30, 20]
C. [50, 40, 30]
D. [30, 20, 10]
Solution
Step 1: Understand ordering by price descending
The prices sorted descending are [50, 40, 30, 20, 10].
Step 2: Apply limit and pluck
Limiting to 3 means we take the first three prices: [50, 40, 30].
Final Answer:
[50, 40, 30] -> Option C
Quick Check:
Order desc + limit 3 = [50, 40, 30] [OK]
Hint: Order desc sorts highest first, limit picks top records [OK]
Common Mistakes:
Forgetting descending order
Mixing ascending with descending
Ignoring limit count
4. What is wrong with this Rails query? User.limit(5).order('name')
medium
A. limit cannot be used with order
B. The order argument should be a symbol, not a string
C. The order method must come before limit
D. The query is valid and will work correctly
Solution
Step 1: Check method chaining order
In Rails, chaining limit before or after order works fine; order does not have to come first.
Step 2: Check argument type for order
Passing a string like 'name' to order is valid syntax in Rails.
Final Answer:
The query is valid and will work correctly -> Option D
Quick Check:
limit + order chaining is flexible = The query is valid and will work correctly [OK]
Hint: Order and limit can be chained in any order [OK]
Common Mistakes:
Thinking order must come before limit
Believing order needs symbol not string
Assuming limit and order cannot combine
5. You want to get the 3 most recent posts but only those with status 'published'. Which Rails query correctly combines filtering, ordering by newest first, and limiting?
hard
A. Post.where(status: 'published').order(created_at: :desc).limit(3)
B. Post.limit(3).order(created_at: :asc).where(status: 'published')
C. Post.order(:created_at).where(status: 'published').limit(3)
D. Post.where(status: 'published').limit(3).order(created_at: :asc)
Solution
Step 1: Filter posts by status 'published'
Use where(status: 'published') to get only published posts.
Step 2: Order posts by newest first
Use order(created_at: :desc) to sort posts from newest to oldest.
Step 3: Limit to 3 records
Use limit(3) to get only the top 3 posts after filtering and ordering.
Final Answer:
Post.where(status: 'published').order(created_at: :desc).limit(3) -> Option A