# frozen_string_literal: true require 'fancy_searchable/searchable' require 'booru/config' # == Schema Information # # Table name: galleries # # id :integer not null, primary key # description :string default(""), not null # image_count :integer default(0), not null # order_position_asc :boolean default(FALSE), not null # spoiler_warning :string default(""), not null # title :string not null # watcher_count :integer default(0), not null # created_at :datetime not null # updated_at :datetime not null # creator_id :integer not null # thumbnail_id :integer not null # # Indexes # # index_galleries_on_creator_id (creator_id) # index_galleries_on_thumbnail_id (thumbnail_id) # # Foreign Keys # # fk_rails_... (creator_id => users.id) ON DELETE => cascade ON UPDATE => cascade # class Gallery < ApplicationRecord include FancySearchable::Searchable include Indexable include Reportable resourcify belongs_to :creator, class_name: 'User', optional: true belongs_to :thumbnail, class_name: 'Post' has_many :gallery_interactions has_many :posts, through: :gallery_interactions has_many :subscriptions, dependent: :delete_all has_many :subscribers, through: :subscriptions, source: :user validates :title, presence: true validates :spoiler_warning, length: { maximum: 20 } validates :description, length: { maximum: Booru::CONFIG.settings[:max_comment_length] } validate :thumbnail_id_is_an_image, if: ->(g) { g.thumbnail_id.present? } after_save :update_index before_destroy :removal_clean_up def after_subscription_change update_index end def position_order order_position_asc ? :asc : :desc end def add(post) gallery_interactions.create(post: post, position: last_position + 1) reindex post update_index Notification.async_notify(self, 'added posts to') self end def remove(post) gallery_interactions.find_by(post: post).destroy reindex post update_index self end private def removal_clean_up to_reindex = posts.map(&:id) gallery_interactions.destroy_all BulkIndexUpdateJob.perform_later('Post', to_reindex) end def reindex(post) post.update_index end def last_position gallery_interactions&.maximum(:position) || -1 end def thumbnail_id_is_an_image errors[:base] << 'Thumbnail ID must be a valid image Post ID' unless Post.find_by_id(thumbnail_id)&.media_type == 'image' end end