Back to list

Ruby on Rails - ActiveRecord Model

Lv.5783@mukitaro14 playsDec 31, 2025

Rails ActiveRecord model with associations, validations, scopes, and callbacks.

preview.ruby
Ruby
1class User < ApplicationRecord
2 has_secure_password
3 has_many :posts, dependent: :destroy
4 has_many :comments, through: :posts
5 belongs_to :organization, optional: true
6
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_email
16 after_create :send_welcome_email
17
18 def full_name
19 "#{first_name} #{last_name}".strip
20 end
21
22 private
23
24 def downcase_email
25 self.email = email.downcase
26 end
27
28 def send_welcome_email
29 UserMailer.welcome(self).deliver_later
30 end
31end

Custom problems are not included in rankings