activemodel

ruby
class SignupForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :account_name, :string
  attribute :email, :string

Shallow Controller, Deep Params: Form Object Pattern

rails activemodel form-object
by codesnips 3 tabs
ruby
class SlugValidator < ActiveModel::Validator
  SLUG_REGEX = /\A[a-z0-9]+(?:-[a-z0-9]+)*\z/

  def validate(record)
    slug = record.send(options[:attribute] || :slug)

Rails validators for custom business logic

rails validations activemodel
by Maya Patel 2 tabs
ruby
# app/validators/order_validator.rb
class OrderValidator < ActiveModel::Validator
  def validate(record)
    validate_order_total(record)
    validate_items_availability(record)
    validate_shipping_address(record)

Custom validators and validation patterns

ruby rails validations
by Sarah Mitchell 3 tabs
ruby
class UserRegistrationForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :email, :string
  attribute :name, :string

Form objects for complex form handling

ruby rails form-objects
by Sarah Mitchell 2 tabs
ruby
class AtLeastOneOfValidator < ActiveModel::Validator
  def validate(record)
    fields = Array(options[:fields])
    raise ArgumentError, "provide :fields" if fields.empty?

    return if fields.any? { |field| filled?(record.public_send(field)) }

Custom Validator for “At Least One of” Fields

rails activemodel validations
by codesnips 3 tabs
ruby
class OnboardingForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  STEPS = %i[account profile preferences].freeze

Multi-Step Wizard Form in Rails with a Form Object and Session-Backed State

rails form-objects activemodel
by codesnips 3 tabs
ruby
class Coupon < ApplicationRecord
  before_validation :normalize_code

  validates :code,
            coupon_code: { min_length: 6 },
            uniqueness: { case_sensitive: false }

Validating Coupon Codes with a Custom EachValidator in Rails

rails validations activerecord
by codesnips 3 tabs
ruby
class AddressForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :line1, :string
  attribute :line2, :string

Rails Nested Address Form Object With Aggregated ActiveModel Errors

rails activemodel form-object
by codesnips 3 tabs