0
0
Ruby on Railsframework~10 mins

Custom validation methods 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 define a custom validation method in a Rails model.

Ruby on Rails
class User < ApplicationRecord
  validate :[1]

  def custom_age_check
    errors.add(:age, "must be at least 18") if age < 18
  end
end
Drag options to blanks, or click blank then click option'
Acheck_age
Bvalidate_age
Ccustom_age_check
Dage_check
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name in the validate call than the method defined.
Forgetting to define the custom validation method.
2fill in blank
medium

Complete the code to add an error message inside the custom validation method.

Ruby on Rails
def check_username
  if username.blank?
    errors.[1](:username, "can't be blank")
  end
end
Drag options to blanks, or click blank then click option'
Aappend
Badd_error
Cpush
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'add_error' or other incorrect method names.
Forgetting to specify the attribute when adding errors.
3fill in blank
hard

Fix the error in the custom validation method to correctly check if email contains '@'.

Ruby on Rails
def email_format
  unless email.[1]('@')
    errors.add(:email, "must contain @")
  end
end
Drag options to blanks, or click blank then click option'
Ainclude?
Bcontains
Chas
Dincludes
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like 'contains' or 'has'.
Forgetting the question mark at the end of 'include?'.
4fill in blank
hard

Fill both blanks to create a custom validation that checks if password length is at least 6.

Ruby on Rails
def password_length_check
  if password.[1] < [2]
    errors.add(:password, "is too short")
  end
end
Drag options to blanks, or click blank then click option'
Alength
B6
Csize
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'size' instead of 'length' (both work but only one is correct here).
Using the wrong number for minimum length.
5fill in blank
hard

Fill all three blanks to create a custom validation that adds an error if age is not between 18 and 65.

Ruby on Rails
def age_range_check
  unless age [1] 18 [2] age [3] 65
    errors.add(:age, "must be between 18 and 65")
  end
end
Drag options to blanks, or click blank then click option'
A>=
B<=
C&&
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using '||' instead of '&&' which allows invalid ages.
Reversing the comparison operators.