osem-fcy/app/models/comment.rb

70 lines
2 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
class Comment < ApplicationRecord
acts_as_nested_set scope: %i(commentable_id commentable_type)
validates :body, presence: true
validates :user, presence: true
after_create :send_notification
2013-01-07 09:04:09 +01:00
# NOTE: install the acts_as_votable plugin if you
# want user to vote on the quality of comments.
#acts_as_votable
2016-12-29 03:17:33 -05:00
belongs_to :commentable, counter_cache: true, polymorphic: true
2013-01-07 09:04:09 +01:00
# NOTE: Comments belong to a user
belongs_to :user
has_paper_trail on: %i(create destroy), meta: { conference_id: :conference_id }
2013-01-07 09:04:09 +01:00
# Helper class method that allows you to build a comment
# by passing a commentable object, a user_id, and comment text
# example in readme
def self.build_from(obj, user_id, comment)
new \
2014-07-21 14:49:05 +02:00
commentable: obj,
2018-11-13 18:01:49 -08:00
body: comment,
user_id: user_id
2013-01-07 09:04:09 +01:00
end
#helper method to check if a comment has children
def has_children?
children.any?
2013-01-07 09:04:09 +01:00
end
# Helper class method to lookup all comments assigned
# to all commentable types for a given user.
scope :find_comments_by_user, lambda { |user|
2014-07-21 14:49:05 +02:00
where(user_id: user.id).order('created_at DESC')
2013-01-07 09:04:09 +01:00
}
# Helper class method to look up all comments for
# commentable class name and commentable id.
scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id|
2014-07-21 14:49:05 +02:00
where(commentable_type: commentable_str.to_s, commentable_id: commentable_id).order('created_at DESC')
2013-01-07 09:04:09 +01:00
}
scope :find_since_last_login, lambda { |user|
if user.last_sign_in_at
where(created_at: (user.last_sign_in_at..Time.now)).order(created_at: :desc)
else
none
end
}
2013-01-07 09:04:09 +01:00
# Helper class method to look up a commentable object
# given the commentable class name and id
def self.find_commentable(commentable_str, commentable_id)
commentable_str.constantize.find(commentable_id)
end
private
def send_notification
2016-04-22 11:29:38 +02:00
EventCommentMailJob.perform_later(self)
end
def conference_id
commentable.program.conference_id
end
2014-06-23 19:07:50 +03:00
end