Table: RailsNotes
User: dreamable
Created at: 2021-02-01 11:13:36 UTC
Updated at: 2021-02-01 11:15:35 UTC
Reference:(Table ID 3, Record ID 17)

标题 :
mutual friends
笔记 :
class CreateFriendships < ActiveRecord::Migration[6.0]
  def change
    create_table :friendships do |t|
      t.references :inviter, null: false, foreign_key: {to_table: "users"}
      t.references :invitee, null: false, foreign_key: {to_table: "users"}
      t.integer :status, null: false, default: 0

      t.timestamps
    end
    add_index :friendships, :status
  end
end
  • Models
# app/models/friendships
class Friendship < ApplicationRecord
  belongs_to :invitee, class_name: "User"
  belongs_to :inviter, class_name: "User"
  enum status: {pending: 0, accepted: 1},     _suffix: true, _prefix: :is
end
# app/models/users
  has_many :friendships_as_invitee, class_name: "Friendship", foreign_key: :invitee_id
  has_many :friendships_as_inviter, class_name: "Friendship", foreign_key: :inviter_id
  def friends
    ids1 = friendships_as_invitee.where(status: :accepted).pluck(:inviter_id)
    ids2 = friendships_as_inviter.where(status: :accepted).pluck(:invitee_id)
    User.where(id: ids1+ids2)
  end
  def all_friends
    ids1 = friendships_as_invitee.pluck(:inviter_id)
    ids2 = friendships_as_inviter.pluck(:invitee_id)
    User.where(id: ids1+ids2)
  end
  def pending_friends
    ids1 = friendships_as_invitee.where(status: :pending).pluck(:inviter_id)
    ids2 = friendships_as_inviter.where(status: :pending).pluck(:invitee_id)
    User.where(id: ids1+ids2)
  end
  def pending_inviters
    ids = friendships_as_invitee.where(status: :pending).pluck(:inviter_id)
    User.where(id: ids)
  end
  def pending_invitees
    ids = friendships_as_inviter.where(status: :pending).pluck(:invitee_id)
    User.where(id: ids)
  end
Tag: