You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
educoder/app/models/discuss.rb

81 lines
2.6 KiB

6 years ago
class Discuss < ApplicationRecord
default_scope { order(created_at: :desc) }
belongs_to :user
belongs_to :parent, class_name: 'Discuss', foreign_key: :parent_id, optional: true
has_many :children, -> { reorder(created_at: :asc) }, class_name: 'Discuss', foreign_key: :parent_id
has_many :praise_treads, as: :praise_tread_object, dependent: :destroy
6 years ago
has_many :tidings, as: :container, dependent: :destroy
has_one :praise_tread_cache, as: :object, dependent: :destroy
6 years ago
belongs_to :dis, polymorphic: true
6 years ago
belongs_to :challenge, optional: true
5 years ago
validate :validate_sensitive_string
5 years ago
validates :content, length: { maximum: 2000, too_long: "不能超过2000个字符" }
6 years ago
after_create :send_tiding
scope :children, -> (discuss_id){ where(parent_id: discuss_id).includes(:user).reorder(created_at: :asc) }
def has_parent?
parent_id.present?
end
def username
user.full_name
end
def can_deleted?(user)
user.admin? || user.id == user_id
end
def game_url(shixun, user)
return '' unless shixun.has_manager?(user)
game = Game.joins(:challenge).where(challenges: { shixun_id: shixun.id, position: position || 1 })
.select(:identifier).find_by(user_id: user_id)
"/tasks/#{game&.identifier}"
end
# def contents(shixun, user)
# return content unless hidden?
#
# shixun.has_manager?(user) ? content : ''
# end
6 years ago
def child_discuss(user)
Discuss.where(parent_id: self.id).includes(:user).reorder(created_at: :asc)
end
6 years ago
def child_discuss_count
Discuss.where(root_id: id).count
end
6 years ago
private
def send_tiding
5 years ago
if dis_type == 'Shixun'
5 years ago
send_user_id = has_parent? ? parent.user_id : Challenge.find(challenge_id).user_id
5 years ago
parent_container_type = 'Challenge'
challenge_id = challenge_id
5 years ago
extra = ''
5 years ago
elsif dis_type == 'Hack'
5 years ago
send_user_id = has_parent? ? parent.user_id : Hack.find(dis_id).user_id
5 years ago
parent_container_type = 'Hack'
5 years ago
challenge_id = dis_id
5 years ago
extra = HackUserLastestCode.where(user_id: user_id, hack_id: dis_id).first&.identifier
5 years ago
end
6 years ago
base_attrs = {
5 years ago
trigger_user_id: user_id, parent_container_id: challenge_id, parent_container_type: parent_container_type,
5 years ago
belong_container_id: dis_id, belong_container_type: dis_type, viewed: 0, tiding_type: 'Comment', extra: extra
6 years ago
}
5 years ago
tidings.create!(base_attrs.merge(user_id: send_user_id))
6 years ago
end
5 years ago
def validate_sensitive_string
raise("内容包含敏感词汇,请重新输入") unless HarmoniousDictionary.clean?(content)
end
6 years ago
end