Skip to content

Instantly share code, notes, and snippets.

@trappist
Last active December 30, 2015 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trappist/7809591 to your computer and use it in GitHub Desktop.
Save trappist/7809591 to your computer and use it in GitHub Desktop.
class Conversation < ActiveRecord::Base
belongs_to :initiator, :class_name => '::User'
belongs_to :recipient, :class_name => '::User'
has_many :messages
has_one :last_message, -> { order("created_at DESC") }, :class_name => '::Message'
scope :visible, -> do
joins("LEFT OUTER JOIN blockings b ON (b.blocker_id=conversations.initiator_id AND b.blocked_id=conversations.recipient_id) OR (b.blocked_id=conversations.initiator_id AND b.blocker_id=conversations.recipient_id)").where("b.id IS NULL")
end
scope :between, ->(user1,user2) { with(user1).with(user2) }
scope :with, ->(other) { where("? IN (initiator_id,recipient_id)", other.id) }
scope :recent, -> { order("updated_at" => :desc) }
scope :unread, -> { where("messages.read" => false) } # always do includes(:last_message) for this
delegate :read?, :to => :last_message
def other(user)
initiator == user ? recipient : initiator
end
def accessible?
!!Conversation.visible.where(:id => self.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment