topic.rb 1.4 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
class Topic < ActiveRecord::Base
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
  named_scope :written_before, lambda { |time|
    { :conditions => ['written_on < ?', time] }
  }
  named_scope :approved, :conditions => {:approved => true}
  named_scope :replied, :conditions => ['replies_count > 0']
  named_scope :anonymous_extension do
    def one
      1
    end
  end
  module NamedExtension
    def two
      2
    end
  end
  module MultipleExtensionOne
    def extension_one
      1
    end
  end
  module MultipleExtensionTwo
    def extension_two
      2
    end
  end
  named_scope :named_extension, :extend => NamedExtension
  named_scope :multiple_extensions, :extend => [MultipleExtensionTwo, MultipleExtensionOne]
  
30
  has_many :replies, :dependent => :destroy, :foreign_key => "parent_id"
D
Initial  
David Heinemeier Hansson 已提交
31
  serialize :content
J
Jeremy Kemper 已提交
32

D
Initial  
David Heinemeier Hansson 已提交
33
  before_create  :default_written_on
34
  before_destroy :destroy_children
D
Initial  
David Heinemeier Hansson 已提交
35 36

  def parent
37
    Topic.find(parent_id)
D
Initial  
David Heinemeier Hansson 已提交
38
  end
J
Jeremy Kemper 已提交
39

40 41 42 43
  # trivial method for testing Array#to_xml with :methods
  def topic_id
    id
  end
J
Jeremy Kemper 已提交
44

45

D
Initial  
David Heinemeier Hansson 已提交
46
  protected
47 48 49 50 51
    def approved=(val)
      @custom_approved = val
      write_attribute(:approved, val)
    end

D
Initial  
David Heinemeier Hansson 已提交
52 53 54 55 56 57 58
    def default_written_on
      self.written_on = Time.now unless attribute_present?("written_on")
    end

    def destroy_children
      self.class.delete_all "parent_id = #{id}"
    end
59 60 61 62 63 64 65

    def after_initialize
      if self.new_record?
        self.author_email_address = 'test@test.com'
      end
    end
end