问题描述
即使使用了 slug,URL 仍然显示 id 而不是标题.代码如下
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
结束
发布模型
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
我希望链接是localhost:8080/posts/this+is+the+title"而不是localhost:8080/posts/2"
I would want the link to be 'localhost:8080/posts/this+is+the+title' and not 'localhost:8080/posts/2'
推荐答案
我也遇到了这个问题.当我链接到我的资源的显示操作时,我会在 url 中获取 id
而不是我的 slug.虽然我可以输入 slugged url 并且它也可以正常工作(我只是无法链接到 slugged url).事实证明,我必须使用命名的路由助手作为friendly_id 来显示 url 中的 slug(我使用的是老式的 controller: 'posts', action: 'show', id: post.id
在我的 link_to
助手中).在你的情况下,我会尝试改变:
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 %>
到
<%= link_to post.title, post_path(post) %>
此外,friendly_id 5.0 版要求您将控制器中的 Model.find
更改为 Model.friendly.find
(除非您明确覆盖它config/initializers/friendly_id.rb
.由于这是一个较旧的帖子,它可能不适用于您,但我想我还是会添加它.尝试更改:
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
到
def show
@post = Post.friendly.find(params[:id])
end
希望有帮助!
这篇关于Friendly_ID Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!