Search code examples
ruby-on-railsscopes

Can you have a scope which checks from absence?


I have an Invites table in my database and when i'm perform a task as a user I want to pass an Event.id to a scope User.not_invited_to(event)

How do I build this scope to check if the user ID is NOT in there?

class User
  has_many :invites, :foreign_key => 'participant_id'
  ...
end

class Invite
  belongs_to :participant, :class_name => "User", :foreign_key => "participant_id"
  ...
end

Solution

  • You can use event.invite_ids:

    scope :not_invited, lambda { |event| where("id not in (?)", event.invite_ids) }