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

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

11
  belongs_to :post, counter_cache: true
12 13 14
  belongs_to :author,   polymorphic: true
  belongs_to :resource, polymorphic: true

15
  has_many :ratings
J
Jeremy Kemper 已提交
16

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

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

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

  module OopsExtension
    def destroy_all(*)
      raise OopsError
    end
  end

  default_scope { extending OopsExtension }

33 34
  scope :oops_comments, -> { extending OopsExtension }

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

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

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

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

  def to_s
    body
  end
56 57
end

58
class SpecialComment < Comment
59
  default_scope { where(deleted_at: nil) }
60
end
61

62 63 64
class SubSpecialComment < SpecialComment
end

65
class VerySpecialComment < Comment
66
end
67 68 69

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

71 72 73
  after_save do |comment|
    comment.post.update_attributes(body: "Automatically altered")
  end
74
end
75 76

class CommentWithDefaultScopeReferencesAssociation < Comment
77
  default_scope -> { includes(:developer).order("developers.name").references(:developer) }
78 79
  belongs_to :developer
end
80 81 82 83 84 85

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