带有“/"和 Slug 的 Rails RESTful 路由 [英] Rails RESTful Routing With '/' and Slugs

查看:33
本文介绍了带有“/"和 Slug 的 Rails RESTful 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望做一些类似于 wordpress slug 的事情,其中​​我有一个这样的 URL,同时保持 RESTful 路由:

I am looking to do something similar a wordpress slug where I have a URL like this while maintaining RESTful routing:

http://foo.com/blog/2009/12/04/article-title

我对保持 RESTFUL 路由感兴趣的原因是我无法使用很多插件,因为我使用的是自定义路由.

The reason I am interested in keep RESTFUL routing is that I am unable to use many plugins because I am using custom routes.

我已经完成了 RESTful 外观:

I have already done the RESTful appearance with:

map.connect   '/blog/:year/:mon/:day/:slug',
              :controller => 'posts', :action => 'show',
                :year => /\d{4}/, :month => /\d{2}/,
                :day => /\d{2}/, :slug => /.+/,
                :requirements => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/, :slug => /.+/ }

为了编写链接,我必须编写自定义的 link_to 助手来生成正确的 URL.我真的很想让这个 RESTful 并让 link_to post_path( @post ) 产生上面的 URL 和 link_to edit_post_path(@post) ...article-title/edit

In order to write the links, I had to write custom link_to helpers to generate the proper URLs. I really would like to make this RESTful and have the link_to post_path( @post ) yield the URL above and the link_to edit_post_path(@post) ...article-title/edit

我也有 :has_many => [:comments] 并且我希望它也能工作.我尝试过的 link_to 如下所示:

I also have :has_many => [:comments] and I would that to work as well. The link_to that I have tried looks like this:

 'posts', :action => 'show', :year => recent_post.datetime.year.to_s,
            :month => sprintf('%.2d', recent_post.datetime.mon.to_i),
            :day => sprintf('%.2d', recent_post.datetime.mday.to_i),
            :slug => recent_post.slug %>

并产生这个(这不是我想要的):

and yields this (which isn't what I want):

http://foo.com/posts/show?day=30&month=11&slug=welcome-to-support-skydivers&year=2009

我不确定我做错了什么.甚至有可能做到这一点吗?

I'm not sure what I am doing wrong. Is it even possible to accomplish this?

推荐答案

我认为它不起作用,因为您没有使用自定义路由.我一直这样做.我只是设置了一个简单的自定义路由:

I think it's not working because you're not using a custom route. I do this all of the time. I simply setup a simple custom route:

map.present_page '/blog/:year/:month/:day/:slug',
          :controller => 'posts', :action => 'show'

那么你应该能够做到:

present_page_path(:year => 2009, 
                  :month => "December", 
                  :day => "13", 
                  :slug => "just-an-example")

您获得查询字符串的原因很可能是因为 rails 没有与您的路线建立连接.使用命名路由明确告诉 rails 使用该路由.如果这能帮您解决问题,请告诉我!

The reason you're getting a query string is most likely because rails isn't making the connection to your route for whatever reason. Using a named route explicitly tells rails to use that route. Let me know if that solves it for you!

这篇关于带有“/"和 Slug 的 Rails RESTful 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆