Sha256: 81152e6380538f3c1da044f3f6ba111db756d49ea299f68f935991d23a0953e4

Contents?: true

Size: 906 Bytes

Versions: 1

Compression:

Stored size: 906 Bytes

Contents

module Discussion
  class CommentRead < ActiveRecord::Base
    attr_accessible :comment_id, :user_id
    belongs_to :user, class_name: Discussion.user_class
    belongs_to :comment, class_name: 'Discussion::Comment'

    validates :user_id, :comment_id, presence: true

    scope :by, ->(user) { where(user_id: user) }
    after_save :sync_thread_read

    private
    def sync_thread_read
      if (self.read_at_changed? or self.id_changed?) and self.comment.commentable.kind_of?(Discussion::Thread)
        scope = self.comment.commentable.thread_reads.by(self.user_id)
        thread_read = scope.first || scope.new

        total_unread = self.comment.commentable.comments.joins(:comment_reads).
            where('discussion_comment_reads.read_at IS NULL AND user_id=?', user.id).count(distinct: true)

        thread_read.read = total_unread == 0

        thread_read.save
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
discussion-0.0.1 app/models/discussion/comment_read.rb