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
  belongs_to :author,   polymorphic: true
  belongs_to :resource, polymorphic: true
12
  belongs_to :developer
13

14
  has_many :ratings
J
Jeremy Kemper 已提交
15

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

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

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

  module OopsExtension
    def destroy_all(*)
      raise OopsError
    end
  end

  default_scope { extending OopsExtension }

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

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

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

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

  def to_s
    body
  end
53 54
end

55 56
class SpecialComment < Comment
end
57

58 59 60
class SubSpecialComment < SpecialComment
end

61
class VerySpecialComment < Comment
62
end
63 64 65

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

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

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