-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfriendship.rb
More file actions
65 lines (53 loc) · 2.25 KB
/
Copy pathfriendship.rb
File metadata and controls
65 lines (53 loc) · 2.25 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true
# == Schema Information
#
# Table name: friendships
#
# id :bigint not null, primary key
# status :integer default("pending"), not null
# created_at :datetime not null
# updated_at :datetime not null
# addressee_id :bigint not null
# requester_id :bigint not null
#
# Indexes
#
# index_friendships_on_addressee_id (addressee_id)
# index_friendships_on_addressee_id_and_status (addressee_id,status)
# index_friendships_on_requester_id (requester_id)
# index_friendships_on_requester_id_and_addressee_id (requester_id,addressee_id) UNIQUE
# index_friendships_on_requester_id_and_status (requester_id,status)
# index_friendships_on_unordered_pair (LEAST(requester_id, addressee_id), GREATEST(requester_id, addressee_id)) UNIQUE
#
# Foreign Keys
#
# fk_rails_... (addressee_id => users.id)
# fk_rails_... (requester_id => users.id)
#
class Friendship < ApplicationRecord
include EncodedIds::HashidIdentifiable
set_public_id_prefix :frn, min_hash_length: 10
belongs_to :requester, class_name: "User"
belongs_to :addressee, class_name: "User"
enum :status, { pending: 0, accepted: 1 }, default: :pending
validates :requester_id, uniqueness: { scope: :addressee_id, message: "friendship already exists" }
validate :cannot_friend_self
validate :no_reverse_friendship_exists, on: :create
scope :involving, ->(user) { where(requester: user).or(where(addressee: user)) }
scope :pending_for, ->(user) { pending.where(addressee: user) }
scope :outgoing_from, ->(user) { pending.where(requester: user) }
scope :accepted_for, ->(user) { accepted.involving(user) }
def friend_for(user)
requester_id == user.id ? addressee : requester
end
def requester?(user) = requester_id == user.id
def addressee?(user) = addressee_id == user.id
private
def cannot_friend_self
errors.add(:addressee, "cannot be yourself") if requester_id == addressee_id
end
def no_reverse_friendship_exists
return unless Friendship.exists?(requester_id: addressee_id, addressee_id: requester_id)
errors.add(:base, "A friendship request already exists between these users")
end
end