From 835af696703484208882a70cc5dd47c5838ecf58 Mon Sep 17 00:00:00 2001 From: Star Rauchenberger Date: Thu, 12 Oct 2023 17:10:34 -0400 Subject: Added blog post commenting --- app/models/blog.rb | 2 ++ app/models/comment.rb | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 app/models/comment.rb (limited to 'app/models') diff --git a/app/models/blog.rb b/app/models/blog.rb index 415167c..b677e2b 100644 --- a/app/models/blog.rb +++ b/app/models/blog.rb @@ -3,6 +3,8 @@ class Blog < ApplicationRecord acts_as_taggable + has_many :comments + validates :title, presence: true validates :body, presence: true, if: :published validates :slug, presence: true, format: /\A[-a-z0-9]+\z/, if: :published diff --git a/app/models/comment.rb b/app/models/comment.rb new file mode 100644 index 0000000..9697100 --- /dev/null +++ b/app/models/comment.rb @@ -0,0 +1,36 @@ +class Comment < ApplicationRecord + extend Enumerize + + belongs_to :blog + + validates :body, presence: true + validates :username, presence: true + validates :email, presence: true, format: URI::MailTo::EMAIL_REGEXP + + scope :published_and_ordered, -> { where(status: :published).order(published_at: :asc) } + + enumerize :status, + in: [:published, :pending, :rejected], + default: :published, + predicates: true + + before_save :set_published_at + + def gravatar_url + hash = Digest::MD5.hexdigest(email) + "https://www.gravatar.com/avatar/#{hash}?size=40&default=identicon&rating=g" + end + + private + + def set_published_at + if self.published? + if self.published_at.blank? + self.published_at = DateTime.now + end + else + self.published_at = nil + end + end + +end -- cgit 1.4.1