comment.rb 2.3 KB
Newer Older
1 2
# frozen_string_literal: true

3 4 5
# `counter_cache` requires association class before `attr_readonly`.
class Post < ActiveRecord::Base; end

6
class Comment < ActiveRecord::Base
7
  scope :limit_by, lambda { |l| limit(l) }
J
Jon Leighton 已提交
8 9
  scope :containing_the_letter_e, -> { where("comments.body LIKE '%e%'") }
  scope :not_again, -> { where("comments.body NOT LIKE '%again%'") }
10
  scope :for_first_post, -> { where(post_id: 1) }
J
Jon Leighton 已提交
11
  scope :for_first_author, -> { joins(:post).where("posts.author_id" => 1) }
12
  scope :created, -> { all }
13

14
  belongs_to :post, counter_cache: true
15 16 17
  belongs_to :author,   polymorphic: true
  belongs_to :resource, polymorphic: true

18
  has_many :ratings
J
Jeremy Kemper 已提交
19

20
  belongs_to :first_post, foreign_key: :post_id
T
Takashi Kokubun 已提交
21
  belongs_to :special_post_with_default_scope, foreign_key: :post_id
22

23 24
  has_many :children, class_name: "Comment", foreign_key: :parent_id
  belongs_to :parent, class_name: "Comment", counter_cache: :children_count
25

26 27 28 29 30 31 32 33 34 35
  class ::OopsError < RuntimeError; end

  module OopsExtension
    def destroy_all(*)
      raise OopsError
    end
  end

  default_scope { extending OopsExtension }

36 37
  scope :oops_comments, -> { extending OopsExtension }

38 39 40 41 42
  # Should not be called if extending modules that having the method exists on an association.
  def self.greeting
    raise
  end

43
  def self.what_are_you
44
    "a comment..."
45
  end
J
Jeremy Kemper 已提交
46

47
  def self.search_by_type(q)
48
    where("#{QUOTED_TYPE} = ?", q)
49
  end
50 51 52 53

  def self.all_as_method
    all
  end
54
  scope :all_as_scope, -> { all }
55 56 57 58

  def to_s
    body
  end
59 60
end

61
class SpecialComment < Comment
62
  has_one :author, through: :post
63
  default_scope { where(deleted_at: nil) }
64 65 66 67

  def self.what_are_you
    "a special comment..."
  end
68
end
69

70 71 72
class SubSpecialComment < SpecialComment
end

73
class VerySpecialComment < Comment
74
end
75 76 77

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

79 80 81
  after_save do |comment|
    comment.post.update_attributes(body: "Automatically altered")
  end
82
end
83 84

class CommentWithDefaultScopeReferencesAssociation < Comment
85
  default_scope -> { includes(:developer).order("developers.name").references(:developer) }
86 87
  belongs_to :developer
end
88 89 90 91 92 93

class CommentWithAfterCreateUpdate < Comment
  after_create do
    update_attributes(body: "bar")
  end
end