list_account.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: list_accounts
  5. #
  6. # id :bigint(8) not null, primary key
  7. # list_id :bigint(8) not null
  8. # account_id :bigint(8) not null
  9. # follow_id :bigint(8)
  10. # follow_request_id :bigint(8)
  11. #
  12. class ListAccount < ApplicationRecord
  13. belongs_to :list
  14. belongs_to :account
  15. belongs_to :follow, optional: true
  16. belongs_to :follow_request, optional: true
  17. validates :account_id, uniqueness: { scope: :list_id }
  18. validate :validate_relationship
  19. before_validation :set_follow
  20. private
  21. def set_follow
  22. return if list.account_id == account.id
  23. self.follow = Follow.find_by!(account_id: list.account_id, target_account_id: account.id)
  24. rescue ActiveRecord::RecordNotFound
  25. self.follow_request = FollowRequest.find_by!(account_id: list.account_id, target_account_id: account.id)
  26. end
  27. def validate_relationship
  28. return if list.account_id == account_id
  29. errors.add(:account_id, 'follow relationship missing') if follow_id.nil? && follow_request_id.nil?
  30. errors.add(:follow, 'mismatched accounts') if follow_id.present? && follow.target_account_id != account_id
  31. errors.add(:follow_request, 'mismatched accounts') if follow_request_id.present? && follow_request.target_account_id != account_id
  32. end
  33. end