Skip to content

Commit

Permalink
增加 slug 的唯一验证,并自动修正非法字符。
Browse files Browse the repository at this point in the history
增加 title, body, summary 的必填验证。
  • Loading branch information
huacnlee committed Feb 28, 2017
1 parent 16e6b6a commit 8e64b56
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app/models/post.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@ class Post < ApplicationRecord

enum status: %i(upcoming published rejected)

validates :slug, uniqueness: true, if: Proc.new { |post| post.slug.present? }
validates :title, :summary, :body, presence: true

counter :hits

before_save :generate_summary
before_create :generate_published_at
before_validation :safe_slug

def to_param
self.slug.blank? ? self.id : self.slug
Expand All @@ -33,6 +37,11 @@ def published!

private

def safe_slug
self.slug.downcase!
self.slug.gsub!(/[^a-z0-9]/i, '-')
end

def generate_published_at
self.published_at = Time.now
end
Expand Down

0 comments on commit 8e64b56

Please sign in to comment.