Back to listRuby
Ruby on Rails - ActiveRecord Model
Lv.5783@mukitaro14 playsDec 31, 2025
Rails ActiveRecord model with associations, validations, scopes, and callbacks.
preview.ruby
1class User < ApplicationRecord2 has_secure_password3 has_many :posts, dependent: :destroy4 has_many :comments, through: :posts5 belongs_to :organization, optional: true6 7 validates :email, presence: true,8 uniqueness: { case_sensitive: false },9 format: { with: URI::MailTo::EMAIL_REGEXP }10 validates :username, presence: true, length: { in: 3..30 }11 12 scope :active, -> { where(active: true) }13 scope :created_after, ->(date) { where('created_at > ?', date) }14 15 before_save :downcase_email16 after_create :send_welcome_email17 18 def full_name19 "#{first_name} #{last_name}".strip20 end21 22 private23 24 def downcase_email25 self.email = email.downcase26 end27 28 def send_welcome_email29 UserMailer.welcome(self).deliver_later30 end31endCustom problems are not included in rankings