前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rails里应用Friendly Id

Rails里应用Friendly Id

作者头像
用户2183996
发布2018-06-28 10:56:18
3950
发布2018-06-28 10:56:18
举报
文章被收录于专栏:技术沉淀技术沉淀

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:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.

代码语言:javascript
复制
class Post < ActiveRecord::Base
    validates(:title, :content, presence: true)
    extend FriendlyId
    friendly_id :title, use: :slugged
end

Edit Controller

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

代码语言:javascript
复制
class PostsController < ApplicationController
    private

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

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

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:

代码语言:javascript
复制
heroku run rake db:migrate
heroku run rails c
Post.find_each(&:save)
exit
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.06.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Change Default URL
  • Add Gem
  • Create Friendly Id Slugs
  • Edit Model
  • Edit Controller
  • One More Thing
  • Deploy to Heroku
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档