beast rev 2066
[beast-modified.git] / app / models / post.rb
blob991572895254e51eb42ef1a3b9aa54c855312453
1 class Post < ActiveRecord::Base
2   def self.per_page() 25 end
4   belongs_to :forum
5   belongs_to :user
6   belongs_to :topic
8   format_attribute :body
9   before_create { |r| r.forum_id = r.topic.forum_id }
10   after_create  :update_cached_fields
11   after_destroy :update_cached_fields
13   validates_presence_of :user_id, :body, :topic
14   attr_accessible :body
15   
16   def editable_by?(user)
17     user && (user.id == user_id || user.admin? || user.moderator_of?(topic.forum_id))
18   end
19   
20   def to_xml(options = {})
21     options[:except] ||= []
22     options[:except] << :topic_title << :forum_name
23     super
24   end
25   
26   protected
27     # using count isn't ideal but it gives us correct caches each time
28     def update_cached_fields
29       Forum.update_all ['posts_count = ?', Post.count(:id, :conditions => {:forum_id => forum_id})], ['id = ?', forum_id]
30       User.update_all  ['posts_count = ?', Post.count(:id, :conditions => {:user_id => user_id})],   ['id = ?', user_id]
31       topic.update_cached_post_fields(self)
32     end
33 end