2016-07-25 27 views
0

在我的Rails应用中,我有一个帖子部分允许用户提交内容。默认情况下,新帖子的URL约定将类似yoursite/posts/8。我想知道是否有人知道是否有可能为用户创建一个自定义URL路由的方法,如制作一个新的帖子,然后有一个字符串“自定义URL”,因此它变得像'yoursite/posttopic'.任何人都知道如何去做这件事?谢谢!Rails:邮件的自定义URL

邮政架构是这样的:

create_table "posts", force: :cascade do |t| 
    t.string "title" 
    t.text  "body" 
    t.datetime "created_at",   null: false 
    t.datetime "updated_at",   null: false 
    t.integer "user_id" 
    t.string "image_file_name" 
    t.string "image_content_type" 
    t.integer "image_file_size" 
    t.datetime "image_updated_at" 
    end 
+0

您可能正在寻找[friendly_id(https://github.com/norman/friendly_id)宝石。 –

回答

1

使用friendly_id宝石。从Quick start guide更新例如:

# edit app/models/post.rb 
class Post < ActiveRecord::Base 
    extend FriendlyId 
    friendly_id :title, use: :slugged 
end 

Post.create! title: "posttopic" 

# Change Post.find to Post.friendly.find in your controller 
Post.friendly.find(params[:id]) 
rails server 

现在你可以使用这个:

GET http://localhost:3000/posts/posttopic 
+0

有什么方法可以取出/ posts部分?并只是让它/ 3000/customURL –

+0

当然,在你的'routes.rb'有这个:'资源:职位,路径:'/''。 –

+0

嗨,friendly_Id正是我所需要的。谢谢! –