-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthor.rb
More file actions
42 lines (32 loc) · 1.13 KB
/
author.rb
File metadata and controls
42 lines (32 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# frozen_string_literal: true
# - Create a profile:
# author.build_profile description: 'Just a desc'
# author.save
class Author < ApplicationRecord
# has_many :posts do
# def filtered # Association Extensions
# where('created_at < ?', Date.today)
# end
# end
has_many :posts, dependent: :nullify
has_many :published_posts, -> { published }, class_name: 'Post', dependent: :nullify, inverse_of: :author
has_many :recent_posts, -> { recents }, class_name: 'Post', dependent: :nullify, inverse_of: :author
# has_many :posts, inverse_of: :author, dependent: :nullify
has_one :profile, inverse_of: :author, dependent: :destroy
accepts_nested_attributes_for :profile, allow_destroy: true
validates :email, format: { with: /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\z/i, message: 'Invalid email' }
validate -> {
errors.add( :base, 'Invalid age' ) if !age || age.to_i % 3 == 1
}
# validate :custom
def to_s
"#{name} (#{age})"
end
def stats
[
"Posts: <b>#{posts.count}</b>",
"Published: <b>#{published_posts.count}</b>",
"Recent: <b>#{recent_posts.count}</b>"
]
end
end