Reputation: 486
In my rails app, I have a posts section to allow user submitted content. By default, the convention for URL's for new posts will be something like yoursite/posts/8
. I am wondering if anyone knows if it is possible for there to be a method for users to create a custom URL route for this, such as making a new post and then having a string with "custom URL" so it becomes something like 'yoursite/posttopic'.
Does anyone know how one might go about doing this? Thank you!
Post schema looks like this:
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
Upvotes: 0
Views: 35
Reputation: 5156
Use friendly_id gem. Updated example from its 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
Now you can use this:
GET http://localhost:3000/posts/posttopic
Upvotes: 1