0
0
Ruby on Railsframework~20 mins

Custom validation methods in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom 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 custom validation method adds an error?
Consider a Rails model with a custom validation method that adds an error to an attribute. What is the effect on the model's validity and saving behavior?
Ruby on Rails
class Product < ApplicationRecord
  validate :price_must_be_positive

  def price_must_be_positive
    errors.add(:price, "must be positive") if price && price <= 0
  end
end

product = Product.new(price: -5)
valid = product.valid?
saved = product.save
Avalid is false, saved is false because the error prevents saving
Bvalid is true, saved is true because validations are skipped
Cvalid is false, saved is true because save ignores errors
Dvalid is true, saved is false because save always fails
Attempts:
2 left
💡 Hint
Think about what happens when errors are added to the errors collection in Rails validations.
📝 Syntax
intermediate
2:00remaining
Which custom validation method syntax is correct?
Identify the correct way to define a custom validation method in a Rails model.
Ruby on Rails
class User < ApplicationRecord
  # Which of these custom validation method definitions is correct?

  # Option A
  validate :check_name
  def check_name
    errors.add(:name, "can't be blank") if name.blank?
  end

  # Option B
  validate check_name
  def check_name
    errors.add(:name, "can't be blank") if name.blank?
  end

  # Option C
  validates :check_name
  def check_name
    errors.add(:name, "can't be blank") if name.blank?
  end

  # Option D
  validate :check_name()
  def check_name
    errors.add(:name, "can't be blank") if name.blank?
  end
end
AOption A is correct
BOption B is correct
COption C is correct
DOption D is correct
Attempts:
2 left
💡 Hint
Look at how the validate method expects its argument.
🔧 Debug
advanced
2:00remaining
Why does this custom validation not add errors as expected?
Given the following model code, why is the error not added using the proper method?
Ruby on Rails
class Order < ApplicationRecord
  validate :check_total

  def check_total
    if total < 0
      errors[:total] << "cannot be negative"
    end
  end
end

order = Order.new(total: -10)
order.save
order.errors.full_messages
AUsing errors[:total] << adds errors but does not mark the model invalid
BThe validation method is not called because validate is misspelled
Cerrors.add should be used instead of errors[:total] << to properly add errors
DThe total attribute is missing from the model, so validation is skipped
Attempts:
2 left
💡 Hint
Check how errors are added to the errors collection in Rails.
state_output
advanced
2:00remaining
What is the value of errors after running this custom validation?
Examine the following Rails model and the result of running validations.
Ruby on Rails
class Event < ApplicationRecord
  validate :start_date_cannot_be_in_past

  def start_date_cannot_be_in_past
    if start_date && start_date < Date.today
      errors.add(:start_date, "can't be in the past")
    end
  end
end

event = Event.new(start_date: Date.today - 1)
event.valid?
event.errors.full_messages
A["Start date can't be blank"]
B["Start date can't be in the past"]
C[]
D["Start date is invalid"]
Attempts:
2 left
💡 Hint
Think about what happens when the start_date is before today.
🧠 Conceptual
expert
2:00remaining
Why use custom validation methods instead of built-in validators?
Which reason best explains why a Rails developer would create a custom validation method instead of using built-in validators like validates_presence_of or validates_numericality_of?
ATo automatically generate error messages without writing any code
BBecause built-in validators are deprecated and should not be used
CTo improve performance by avoiding built-in validation overhead
DTo implement complex or conditional validation logic that built-in validators cannot handle
Attempts:
2 left
💡 Hint
Think about when built-in validators are not enough.