Rails里应用Friendly Id

Change Default URL

Sometimes, we want to change the displayed URL because url like /post/4/edit is not descriptive and then friendly_id come into play! Here is a simple guide for using friendly_id in your rails app.

Add Gem

First thing you need to do is to add friendly_id gem to you Gemfile. Just add gem 'friendly_id', '~> 5.1.0' to your Gemfile and run bundle install and restart your server.

Create Friendly Id Slugs

You need to create a table in your database. It's pretty easy to do.

If you want to use friendly id for a new resource, say User, run these commands:

rails generate scaffold user name:string slug:string:uniq
rake db:migrate

If you want to use friendly id for an existing resource, say Post, run these commands:

rails generate migration add_slug_to_posts slug:string:uniq
rake db:migrate

Edit Model

You may need to edit your corresponding model(like User or Post). Change :title in the code to meet your need.

class Post < ActiveRecord::Base
    validates(:title, :content, presence: true)
    extend FriendlyId
    friendly_id :title, use: :slugged

Edit Controller

To get things done, you also need to edit you corresponding controller. Use friendly.find instead of find and permit :slug.

class PostsController < ApplicationController

    def post_params
        params.require(:post).permit(:title, :content, :category, :slug)

    def find_post
        @post = Post.friendly.find(params[:id])

One More Thing

If you use friendly id for your existing resource, you may also need to run this command in rails console Post.find_each(&:save). Then it should work.

Deploy to Heroku

If your app is deployed at heroku, these commands are also need:

heroku run rake db:migrate
heroku run rails c




0 条评论
登录 后参与评论