topic.rb 2.0 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
class Topic < ActiveRecord::Base
2
  named_scope :base
3
  named_scope :written_before, lambda { |time|
4 5 6
    if time
      { :conditions => ['written_on < ?', time] }
    end
7 8
  }
  named_scope :approved, :conditions => {:approved => true}
9 10
  named_scope :rejected, :conditions => {:approved => false}

11 12
  named_scope :by_lifo, :conditions => {:author_name => 'lifo'}
  
13
  named_scope :approved_as_hash_condition, :conditions => {:topics => {:approved => true}}
14
  named_scope 'approved_as_string', :conditions => {:approved => true}
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
  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]
38 39
  
  named_scope :by_rejected_ids, lambda {{ :conditions => { :id => all(:conditions => {:approved => false}).map(&:id) } }}
40

41
  has_many :replies, :dependent => :destroy, :foreign_key => "parent_id"
D
Initial  
David Heinemeier Hansson 已提交
42
  serialize :content
J
Jeremy Kemper 已提交
43

D
Initial  
David Heinemeier Hansson 已提交
44
  before_create  :default_written_on
45
  before_destroy :destroy_children
D
Initial  
David Heinemeier Hansson 已提交
46 47

  def parent
48
    Topic.find(parent_id)
D
Initial  
David Heinemeier Hansson 已提交
49
  end
J
Jeremy Kemper 已提交
50

51 52 53 54
  # trivial method for testing Array#to_xml with :methods
  def topic_id
    id
  end
J
Jeremy Kemper 已提交
55

D
Initial  
David Heinemeier Hansson 已提交
56
  protected
57 58 59 60 61
    def approved=(val)
      @custom_approved = val
      write_attribute(:approved, val)
    end

D
Initial  
David Heinemeier Hansson 已提交
62 63 64 65 66 67 68
    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
69 70 71 72 73 74

    def after_initialize
      if self.new_record?
        self.author_email_address = 'test@test.com'
      end
    end
75
end
76 77 78 79 80 81

module Web
  class Topic < ActiveRecord::Base
    has_many :replies, :dependent => :destroy, :foreign_key => "parent_id", :class_name => 'Web::Reply'
  end
end