class Forum < ActiveRecord::Base include Redmine::SafeAttributes has_many :topics, :class_name => 'Memo', :conditions => "#{Memo.table_name}.parent_id IS NULL", :order => "#{Memo.table_name}.created_at DESC", :dependent => :destroy has_many :memos, :dependent => :destroy, conditions: "parent_id IS NULL" belongs_to :creator, :class_name => "User", :foreign_key => 'creator_id' safe_attributes 'name', 'description', 'topic_count', 'memo_count', 'last_memo_id', 'creator_id' validates_presence_of :name, :creator_id validates_length_of :name, maximum: 50 validates_length_of :description, maximum: 255 validates :name, :uniqueness => true acts_as_taggable scope :by_join_date, order("created_at DESC") def reset_counters! self.class.reset_counters!(id) end def editable_by? user # user && user.logged? || (self.author == usr && usr.allowed_to?(:edit_own_messages, project)) self.creator == user || user.admin? end def destroyable_by? user # user && user.logged? && Forum.find(self.forum_id).creator_id == user.id || user.admin? user.admin? end # Updates topic_count, memo_count and last_memo_id attributes for +board_id+ def self.reset_counters!(forum_id) forum_id = forum_id.to_i update_all("topic_count = (SELECT COUNT(*) FROM #{Memo.table_name} WHERE forum_id=#{forum_id} AND parent_id IS NULL)," + " memo_count = (SELECT COUNT(*) FROM #{Memo.table_name} WHERE forum_id=#{forum_id} AND parent_id IS NOT NULL)," + " last_memo_id = (SELECT MAX(id) FROM #{Memo.table_name} WHERE forum_id=#{forum_id})", ["id = ?", forum_id]) end end