Performance: Custom validation methods
Custom validation methods affect server-side processing time and can indirectly impact user experience by delaying form submission feedback.
class User < ApplicationRecord validates :email, format: { with: URI::MailTo::EMAIL_REGEXP } validates :email, uniqueness: true end
class User < ApplicationRecord validate :check_email_format def check_email_format # Inefficient regex and multiple DB calls if email.present? && !email.match?(/^[\w+\-.]+@[a-z\d\-.]+\.[a-z]+$/i) errors.add(:email, 'is invalid') end if User.where(email: email).exists? errors.add(:email, 'has already been taken') end end end
| Pattern | Server CPU Time | DB Queries | Response Delay | Verdict |
|---|---|---|---|---|
| Custom validation with DB calls | High | Multiple per validation | Increases response time | [X] Bad |
| Built-in validators | Low | Optimized single queries | Minimal delay | [OK] Good |
check_age in a Rails model?validate :method_name to call a custom method.check_age, syntax is validate :check_age.class User < ApplicationRecord
validate :check_name
def check_name
errors.add(:name, "can't be blank") if name.blank?
end
endname = ''?name.blank? is true (empty string).class Product < ApplicationRecord
validate :check_price
def check_price
errors.add(:price, "must be positive") if price <= 0
end
endusername is at least 5 characters and contains no spaces. Which code correctly implements this?validate :username_rules
def username_rules
if username.length < 5 || username.include?(" ")
errors.add(:username, "must be 5+ chars and no spaces")
end
end uses OR logic to add error if username is shorter than 5 or contains spaces, which matches requirements.validates :username, length: { minimum: 5 }, format: { without: /\s/ } uses built-in validations, not custom method. validate :username_rules
def username_rules
errors.add(:username, "invalid") unless username.length >= 5 && !username.include:(" ")
end has syntax error with colon in method call. validate :username_rules
def username_rules
errors.add(:username, "invalid") if username.length <= 5 && username.include?(" ")
end uses wrong comparison (<= 5 excludes 5).Pass the test and this pattern moves unknown