Bird
Raised Fist0
Ruby on Railsframework~20 mins

Uniqueness validation in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Uniqueness Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a duplicate record is saved with uniqueness validation?
Given a Rails model with validates :email, uniqueness: true, what will happen if you try to save two records with the same email?
Ruby on Rails
class User < ApplicationRecord
  validates :email, uniqueness: true
end

user1 = User.create(email: 'test@example.com')
user2 = User.new(email: 'test@example.com')
success = user2.save
AThe second save will succeed but overwrite the first record silently.
BThe second save will succeed and create a duplicate record because uniqueness validation only works on update.
CThe second save will raise a runtime error due to a database constraint violation.
DThe second save will fail and <code>success</code> will be false because the email is not unique.
Attempts:
2 left
💡 Hint
Think about what the uniqueness validation does before saving a record.
📝 Syntax
intermediate
2:00remaining
Which option correctly adds case-insensitive uniqueness validation on username?
You want to ensure usernames are unique regardless of letter case. Which validation code is correct?
Ruby on Rails
class User < ApplicationRecord
  # Add validation here
end
Avalidates_uniqueness_of :username, case_sensitive: false
Bvalidates :username, uniqueness: { case_sensitive: false }
Cvalidates :username, uniqueness: true, case_sensitive: false
Dvalidates :username, unique: { case_sensitive: false }
Attempts:
2 left
💡 Hint
Look for the correct syntax for options inside the uniqueness validator.
🔧 Debug
advanced
3:00remaining
Why does uniqueness validation fail with concurrent record creation?
Consider this code:
class User < ApplicationRecord
  validates :email, uniqueness: true
end

# Two threads run:
User.create(email: 'a@example.com')
User.create(email: 'a@example.com')
Why might both records be created despite the validation?
ABecause uniqueness validation is not atomic and race conditions can allow duplicates before database constraints catch them.
BBecause Rails validations are skipped on create by default.
CBecause the validation only checks for uniqueness on update, not on create.
DBecause the database automatically allows duplicates unless a unique index is added.
Attempts:
2 left
💡 Hint
Think about what happens when two processes check uniqueness at the same time.
❓ state_output
advanced
2:00remaining
What is the value of user.errors[:email] after a failed uniqueness validation?
Given this code:
class User < ApplicationRecord
  validates :email, uniqueness: true
end

user1 = User.create(email: 'dup@example.com')
user2 = User.new(email: 'dup@example.com')
user2.valid?
errors = user2.errors[:email]
What is the value of errors?
A["can't be blank"]
B[] (empty array)
C["has already been taken"]
D["is invalid"]
Attempts:
2 left
💡 Hint
What message does Rails add for uniqueness validation failures?
🧠 Conceptual
expert
3:00remaining
Why should you add a unique index in the database when using uniqueness validation?
Which is the best explanation for adding a unique index on a column that has Rails uniqueness validation?
ATo ensure data integrity at the database level and prevent duplicates even with concurrent writes.
BTo speed up the Rails validation process by caching results in the database.
CBecause Rails validations do not run on production environments by default.
DTo allow Rails to automatically rollback transactions on validation failure.
Attempts:
2 left
💡 Hint
Think about what happens if two users save the same data at the same time.

Practice

(1/5)
1. What does validates :email, uniqueness: true do in a Rails model?
easy
A. Deletes duplicate email records from the database
B. Prevents saving records with duplicate email values
C. Allows multiple records with the same email
D. Automatically encrypts the email field

Solution

  1. Step 1: Understand uniqueness validation purpose

    Uniqueness validation ensures no two records have the same value for the specified field.
  2. Step 2: Apply to the email field

    Using validates :email, uniqueness: true means Rails will check that the email is unique before saving.
  3. Final Answer:

    Prevents saving records with duplicate email values -> Option B
  4. Quick Check:

    Uniqueness validation = prevents duplicates [OK]
Hint: Uniqueness validation stops duplicate field values [OK]
Common Mistakes:
  • Thinking it encrypts data
  • Assuming it deletes duplicates automatically
  • Believing it allows duplicates
2. Which is the correct syntax to add uniqueness validation for a username in a Rails model?
easy
A. validates :username, unique: true
B. validate :username, uniqueness: true
C. validates :username, uniqueness: true
D. validates_uniqueness_of :username, true

Solution

  1. Step 1: Recall Rails validation syntax

    Rails uses validates :field, uniqueness: true for uniqueness validation.
  2. Step 2: Check each option

    validates :username, uniqueness: true matches the correct syntax exactly; others have syntax errors or deprecated style.
  3. Final Answer:

    validates :username, uniqueness: true -> Option C
  4. Quick Check:

    Correct uniqueness syntax = validates :field, uniqueness: true [OK]
Hint: Use 'validates :field, uniqueness: true' syntax [OK]
Common Mistakes:
  • Using 'unique' instead of 'uniqueness'
  • Using 'validate' instead of 'validates'
  • Using deprecated 'validates_uniqueness_of' syntax incorrectly
3. Given this model code:
class User < ApplicationRecord
  validates :email, uniqueness: true
end

What happens if you try to save two users with the same email?
medium
A. The second user fails to save due to validation error
B. Both users save successfully
C. An exception is raised immediately
D. The database automatically rejects the second user

Solution

  1. Step 1: Understand Rails validation behavior

    Uniqueness validation runs before saving and prevents duplicates by adding errors.
  2. Step 2: Effect on saving duplicate email

    The first user saves fine; the second user triggers validation failure and does not save.
  3. Final Answer:

    The second user fails to save due to validation error -> Option A
  4. Quick Check:

    Uniqueness validation blocks duplicates on save [OK]
Hint: Second duplicate save triggers validation error [OK]
Common Mistakes:
  • Thinking both save successfully
  • Expecting a database exception instead of validation error
  • Assuming database rejects without validation
4. Identify the problem in this model code:
class Product < ApplicationRecord
  validates :code, uniqueness: true
  validates :code, presence: true
end

Why might duplicates still be saved?
medium
A. Uniqueness validation is case sensitive by default
B. Presence validation conflicts with uniqueness validation
C. The validations are in the wrong order
D. No unique index exists in the database for code

Solution

  1. Step 1: Understand validation vs database constraints

    Rails validations check before saving but do not guarantee uniqueness at the database level.
  2. Step 2: Check for unique index necessity

    Without a unique database index on code, race conditions can allow duplicates.
  3. Final Answer:

    No unique index exists in the database for code -> Option D
  4. Quick Check:

    Validation alone can't prevent duplicates without DB index [OK]
Hint: Add unique DB index to fully prevent duplicates [OK]
Common Mistakes:
  • Assuming validations alone guarantee uniqueness
  • Confusing presence and uniqueness validations
  • Thinking validation order matters here
5. You want to ensure usernames are unique but case insensitive (e.g., 'User1' and 'user1' count as duplicates). How do you write the validation?
hard
A. validates :username, uniqueness: { case_sensitive: false }
B. validates :username, uniqueness: true, case_sensitive: false
C. validates :username, unique: { case_sensitive: false }
D. validates_uniqueness_of :username, case_sensitive: true

Solution

  1. Step 1: Recall uniqueness validation options

    To make uniqueness case insensitive, use uniqueness: { case_sensitive: false }.
  2. Step 2: Check each option's correctness

    validates :username, uniqueness: { case_sensitive: false } uses correct syntax and option key; others have syntax errors or wrong case sensitivity.
  3. Final Answer:

    validates :username, uniqueness: { case_sensitive: false } -> Option A
  4. Quick Check:

    Case insensitive uniqueness = uniqueness: { case_sensitive: false } [OK]
Hint: Use uniqueness with case_sensitive: false for case insensitivity [OK]
Common Mistakes:
  • Placing case_sensitive outside uniqueness hash
  • Using 'unique' instead of 'uniqueness'
  • Setting case_sensitive to true by mistake
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard