50 行
1.7 KiB
Ruby
50 行
1.7 KiB
Ruby
class Submission < ApplicationRecord
|
|
TARGETS = { 'post_removal' => [Post, PostVersion, :post_id],
|
|
'tag_removal' => [Tag, TagVersion, :tag_id],
|
|
'material_removal' => [Material, MaterialVersion, :material_id] }.freeze
|
|
CATEGORIES = (TARGETS.keys + ['opinion']).freeze
|
|
PAGE_SIZE = 20
|
|
|
|
belongs_to :user
|
|
|
|
validates :category, inclusion: { in: CATEGORIES }
|
|
validates :content, presence: true, length: { maximum: 5000 }
|
|
validates :target_id, absence: true, if: -> { category == 'opinion' }
|
|
validates :target_id, numericality: { only_integer: true,
|
|
greater_than: 0, less_than: 2**63 },
|
|
if: -> { TARGETS.key?(category) }
|
|
validate :validate_target
|
|
|
|
def self.target_scope(category)
|
|
model, version_model = TARGETS.fetch(category)
|
|
HistoryAccess.current(model.all, version_model)
|
|
end
|
|
|
|
def self.public_listing
|
|
return all if HistoryAccess.admin?
|
|
|
|
TARGETS.keys.reduce(where(category: 'opinion')) do |scope, category|
|
|
_model, version_model, key = TARGETS.fetch(category)
|
|
# Keep pre-removal submissions private even after the target is restored.
|
|
boundaries = version_model.where(event_type: 'discard').where(
|
|
version_model.arel_table[:version_no].gteq(arel_table[:target_version_no]))
|
|
scope.or(where(category:, target_id: target_scope(category).select(:id))
|
|
.where.not(target_version_no: nil)
|
|
.where.not(target_id: boundaries.select(key)))
|
|
end
|
|
end
|
|
|
|
private
|
|
|
|
def validate_target
|
|
return unless TARGETS.key?(category) && errors[:target_id].empty?
|
|
target = self.class.target_scope(category).find_by(id: target_id)
|
|
if target
|
|
self.target_version_no = target.version_no if new_record?
|
|
return
|
|
end
|
|
|
|
errors.add(:target_id, :invalid)
|
|
end
|
|
end
|