问题
The URL still shows the id and not the title even after using slug. Code as follows
index.html.erb
<title>Blog!</title>
<h1>List of the Posts</h1>
<% @posts.each do |post| %>
<%= link_to post.title,:id => post.slug%>
<p><%= post.content %></p>
<%= link_to "Edit",edit_post_path(post) %> |
<%= link_to "Delete",post,:confirm=>"Are you sure ?",:method=>:delete %>
<hr />
<% end %>
<p><%= link_to "Add a New Post",new_post_path %></p>
posts_controller.rb
class PostsController < ApplicationController
def index
@posts=Post.all
end
def show
@posts=Post.find(params[:id])
end
end
Post Model
extend FriendlyId
friendly_id :title,use: :slugged
def should_generate_new_friendly_id?
new_record
end
routes.rb
Blog::Application.routes.draw do
get "blog/posts"
resources :posts
end
I would want the link to be 'localhost:8080/posts/this+is+the+title' and not 'localhost:8080/posts/2'
回答1:
I was having trouble with this issue too. When I linked to the show action of my resource, I would get the id
in the url instead of my slug. Although I could type in the slugged url and it would also work fine (I just couldn't link to the slugged url). It turns out that I had to use named route helpers for friendly_id to display the slug in the url (I was using the old-school controller: 'posts', action: 'show', id: post.id
in my link_to
helper). In your case, I would try changing:
<%= link_to post.title, :id => post.slug %>
to
<%= link_to post.title, post_path(post) %>
Also, friendly_id version 5.0 requires that you change Model.find
to Model.friendly.find
in your controller (unless you explicitly override it config/initializers/friendly_id.rb
. Since this is an older post, it might not apply to you, but I thought I'd add it anyway. Try changing:
def show
@post = Post.find(params[:id])
end
to
def show
@post = Post.friendly.find(params[:id])
end
Hope that helps!
来源:https://stackoverflow.com/questions/14893014/friendly-id-ruby-on-rails