【问题标题】:How to remove /posts/ from URL?如何从 URL 中删除 /posts/?
【发布时间】:2016-11-21 17:17:52
【问题描述】:

如何在 URL 中显示没有 /posts/ 的博客文章?

http://www.anthonygalli.com/posts/i-walk-the-line
http://www.anthonygalli.com/posts/50-shades-of-galli
http://www.anthonygalli.com/posts/tips-for-regaining-momentum

缩短版(问题目标):

http://www.anthonygalli.com/i-walk-the-line
http://www.anthonygalli.com/50-shades-of-galli
http://www.anthonygalli.com/tips-for-regaining-momentum

我有 post 作为 MVC。

routes.rb

resources :posts
get    'about'   => 'posts#about'
get    'feed'    => 'posts#feed'
get    'subscribe' => 'posts#subscribe'

【问题讨论】:

  • 你可以使用'/:title' => 'posts#show'resources :posts ,:except => :show
  • 后一行会产生这个错误:undefined local variable or method 'except' for #<ActionDispatch::Routing::Mapper:0x007ff02d549fc8>我希望链接的两个版本都能正常工作,即缩短版本和当前版本@uzaif
  • get :title => 'posts#show' 试试这个

标签: ruby-on-rails ruby model-view-controller routes


【解决方案1】:

将您的 routes.rb 更改为:

resources :posts, path: '/' do
  collection do
    get 'about'
    get 'feed'
    get 'subscribe'
  end
end

有关 Rails 路由检查的文档:http://guides.rubyonrails.org/routing.html

【讨论】:

  • 嘿先生。我遇到了一个问题。我更新了有问题的routes.rb。例如,如果一个人去aboutfeedsubscribe,如果我添加到routes.rb,他们将得到错误ActiveRecord::RecordNotFound (Couldn't find Post): app/controllers/posts_controller.rb:61:in 'find_post'resources :posts, path: '/' 否则效果很好:)
  • 你好!它适用于路线的最新变化吗?
  • 您的答案适用于集合,但由于slug_path 功能,Chris 的答案效果更好。谢谢你的帮助!我在别处给了你道具来弥补它:)
【解决方案2】:

您的路线应更新为如下所示:

resources :posts
get    'about'   => 'posts#about'
get    'feed'    => 'posts#feed'
get    'subscribe' => 'posts#subscribe'
get    ':id'     => 'posts#show', :as => :post_by_slug

如果您想链接到/post/-less 路径,那么 as 选项对于链接到您的新路线很重要:

<%= link_to post.title, post_by_slug_path(post) %>

P。 S. 我相信新路线需要在您的路线中最后列出,以便它之前的路线可以优先。 (否则,尝试访问 /about 会尝试加载带有名为 about 的 slug 的帖子,而不是 posts#about 操作。你应该试试这个,看看这是不是真的。)

【讨论】:

    【解决方案3】:

    Resource 生成标准的 CRUD url,因此您必须专门指定帖子路由。像这样的

    get '/desired-url' => 'posts#index'
    

    【讨论】:

    • 我创建的每个新帖子都会创建一个新的desired post,这样就行不通了。这也是关于显示页面而不是索引页面。感谢您的尝试,虽然好先生!
    猜你喜欢
    • 1970-01-01
    • 2013-03-21
    • 2020-11-11
    • 2021-12-05
    • 2012-05-15
    • 2011-04-12
    • 2012-06-10
    相关资源
    最近更新 更多