Performance: Form object pattern
This pattern affects server-side processing speed and user experience by managing form validations and data handling efficiently.
class UserForm include ActiveModel::Model attr_accessor :name, :addresses_attributes validates :name, presence: true validate :validate_addresses def save return false unless valid? ActiveRecord::Base.transaction do user = User.create!(name: name) addresses_attributes.each { |addr| user.addresses.create!(addr) } end true end private def validate_addresses # custom validation logic end end # In controller @form = UserForm.new(params[:user_form]) if @form.save # success end
class User < ApplicationRecord has_many :addresses validates :name, presence: true validates_associated :addresses end # In controller @user = User.new(user_params) if @user.save # saves user and addresses end
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Model with nested validations | N/A (server-side) | N/A | N/A | [X] Bad |
| Form object with transaction | N/A (server-side) | N/A | N/A | [OK] Good |
Form Object in Rails?ActiveModel::Model module allows plain Ruby objects to behave like ActiveRecord models, including validations.ActiveRecord::Base is for database models, ActionController::Base is for controllers, and ActiveSupport::Concern is for mixins.user_form.valid? return if email is blank?
class UserForm include ActiveModel::Model attr_accessor :email validates :email, presence: true end user_form = UserForm.new(email: '') user_form.valid?
email to be present (not blank).email is an empty string, which fails the presence validation, so valid? returns false.class OrderForm
include ActiveModel::Model
attr_accessor :quantity
validates :quantity, numericality: { greater_than: 0 }
def save
if valid?
Order.create(quantity: quantity)
end
end
endemail, password, and password_confirmation. Which approach correctly ensures password confirmation validation and saves the user if valid?
class RegistrationForm
include ActiveModel::Model
attr_accessor :email, :password, :password_confirmation
validates :email, presence: true
validates :password, presence: true, confirmation: true
def save
if valid?
User.create(email: email, password: password)
end
end
endconfirmation: true option on password automatically validates that password_confirmation matches.save method calls valid? and creates the user if valid, which is the correct pattern.Pass the test and this pattern moves unknown