# Topic is a collection of posts class Topic < ActiveRecord::Base has_many :posts, :exclusively_dependent => true belongs_to :forum has_many :topic_subscriptions, :exclusively_dependent => true has_many :topic_reads, :exclusively_dependent => true has_and_belongs_to_many :tags, :join_table => 'topics_tags' include ErrorRaising # CALLBACKS def before_create self.deleted = 0 end # NORMAL METHODS # Add a reply to the root post in this topic. # TODO: transaction? def add_reply(post) root_post.add_reply(post) end def hidden? (self.deleted == 1) end # Hide topic with all posts def hide self.update_attribute('deleted', 1) self.root_post.hide(:recursive) end # Unhide topic and root post; if recursive, unhide all posts def unhide(recursive=false) self.update_attribute('deleted', 0) self.root_post.unhide(recursive) end # Get the data needed for the topic view. def posts_with_user_data(include_hidden = false) self.posts.find( :all, :include => [:user, :topic], :conditions => (include_hidden ? nil : "posts.deleted = 0"), :order => 'posts.created_at ASC, posts.id ASC' ) end # Get the root post of the topic. def root_post res = posts.find_all("parent_id IS NULL") raise "Data integrity: topic #{} has #{res.size} root posts" if res.size > 1 raise "Data integrity: topic #{} has no root posts" if res.empty? res[0] end def subscribed_by?(user) return false if user.guest? TopicSubscription.count("user_id = #{user.id} and topic_id = #{self.id}") > 0 end def update_last_post_data(last_post=nil) last_post ||= posts.find_first 'deleted=0', 'created_at DESC,id DESC' if last_post self.last_post_created_at = last_post.created_at self.last_post_user_id = last_post.user_id self.last_post_author = last_post.get_display_name end end def update_post_counter self.post_counter = self.posts.count('deleted = 0') end end