Ruby on rails学习:为posts添加唯一id,friendly_id

让你的 posts URL 看起来更加的简洁
更新于: 2022-01-02 16:40:36

安装

# 添加到 Gemfile
gem 'friendly_id', '~> 5.4.0'
# 安装
bundle install

添加 migration

rails g migration AddSlugToUsers slug:uniq
rails generate friendly_id
rails db:migrate

app/models/user.rb

class User < ApplicationRecord
  extend FriendlyId
  friendly_id :name, use: :slugged
end

app/controllers/users_controller.rb

class UserController < ApplicationController
  def show
    @user = User.friendly.find(params[:id])
  end
end

处理已有数据(db/seed.rb)

User.find_each(&:save)

可以抽成 app/models/concerns/with_friendly_id.rb

module WithFriendlyId
  extend ActiveSupport::Concern
  included do
    friendly_id :slugging, use: :slugged
  end

  private

  def slugging
    Digest::SHA1.hexdigest("#{title}-#{id}")[0..12]
  end
end

按这种方式调用 app/models/post.rb

class Post < ApplicationRecord
  extend FriendlyId
  include WithFriendlyId
  # your code..
end

参考

https://github.com/norman/friendly_id

https://hackernoon.com/using-custom-slugs-for-rails-urls-500eb3f58f3c