Friendly_ID Ruby on Rails

扶醉桌前 提交于 2021-02-10 07:26:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!