【问题标题】:Rails: Custom URL For PostsRails:帖子的自定义 URL
【发布时间】:2016-07-25 21:05:26
【问题描述】:

在我的 rails 应用程序中,我有一个帖子部分允许用户提交内容。默认情况下,新帖子的 URL 约定类似于yoursite/posts/8。我想知道是否有人知道是否有可能让用户为此创建自定义 URL 路由,例如创建一个新帖子,然后有一个带有“自定义 URL”的字符串,所以它变成类似于 @987654323 @有谁知道怎么做?谢谢!

发布架构如下所示:

  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

【问题讨论】:

标签: ruby-on-rails content-management-system blogs


【解决方案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

【讨论】:

  • 有什么办法可以取出 /posts 部分吗?并使其成为 /3000/customURL
  • 当然,在您的routes.rb 中有这个:resources :posts, path: '/'
  • 嗨,friendly_Id 正是我所需要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 2013-09-28
  • 2020-10-24
  • 2016-11-29
相关资源
最近更新 更多