comment.rb 1.9 KB
Newer Older
1
class Comment < ActiveRecord::Base
2
  scope :limit_by, lambda { |l| limit(l) }
J
Jon Leighton 已提交
3 4
  scope :containing_the_letter_e, -> { where("comments.body LIKE '%e%'") }
  scope :not_again, -> { where("comments.body NOT LIKE '%again%'") }
5
  scope :for_first_post, -> { where(post_id: 1) }
J
Jon Leighton 已提交
6
  scope :for_first_author, -> { joins(:post).where("posts.author_id" => 1) }
7
  scope :created, -> { all }
8

9
  belongs_to :post, counter_cache: true
10 11 12
  belongs_to :author,   polymorphic: true
  belongs_to :resource, polymorphic: true

13
  has_many :ratings
J
Jeremy Kemper 已提交
14

15
  belongs_to :first_post, foreign_key: :post_id
T
Takashi Kokubun 已提交
16
  belongs_to :special_post_with_default_scope, foreign_key: :post_id
17

18 19
  has_many :children, class_name: "Comment", foreign_key: :parent_id
  belongs_to :parent, class_name: "Comment", counter_cache: :children_count
20

21 22 23 24 25 26 27 28 29 30
  class ::OopsError < RuntimeError; end

  module OopsExtension
    def destroy_all(*)
      raise OopsError
    end
  end

  default_scope { extending OopsExtension }

31 32
  scope :oops_comments, -> { extending OopsExtension }

33 34 35 36 37
  # Should not be called if extending modules that having the method exists on an association.
  def self.greeting
    raise
  end

38
  def self.what_are_you
39
    "a comment..."
40
  end
J
Jeremy Kemper 已提交
41

42
  def self.search_by_type(q)
43
    where("#{QUOTED_TYPE} = ?", q)
44
  end
45 46 47 48

  def self.all_as_method
    all
  end
49
  scope :all_as_scope, -> { all }
50 51 52 53

  def to_s
    body
  end
54 55
end

56 57
class SpecialComment < Comment
end
58

59 60 61
class SubSpecialComment < SpecialComment
end

62
class VerySpecialComment < Comment
63
end
64 65 66

class CommentThatAutomaticallyAltersPostBody < Comment
  belongs_to :post, class_name: "PostThatLoadsCommentsInAnAfterSaveHook", foreign_key: :post_id
67

68 69 70
  after_save do |comment|
    comment.post.update_attributes(body: "Automatically altered")
  end
71
end
72 73

class CommentWithDefaultScopeReferencesAssociation < Comment
74
  default_scope -> { includes(:developer).order("developers.name").references(:developer) }
75 76
  belongs_to :developer
end