ruby-on-rails - 在Rails中做 “/blogs/:year/:month/:day/:permalink”路线的最佳方法?

标签 ruby-on-rails resources routing

我有一个带有Blog资源的blogs_controller,所以现在您的典型路线如下:

/blogs/new
/blogs/1
/blogs/1/edit #etc

但是,这就是我想要的:
/blogs/new
/blogs/2010/01/08/1-to_param-or-something
/blogs/2010/01/08/1-to_param-or-something/edit #etc
...
/blogs/2010/01 # all posts for January 2010, but how to specify custom action?

我知道我可以结合使用map.resources和map.connect来做到这一点,但是我有很多 View 通过“new_blog_path”等链接到其他页面,我不想去编辑那些。单独使用map.resources是否有可能?这可能并不容易,但是我并不反对聪明。我在想类似的东西:
map.resources :blogs, :path_prefix => ':year/:month/:day', :requirements => {:year => /\d{4}/, :month => /\d{1,2}/, :day => /\d{1,2}/}

但是我不确定它如何与“new”或“create”之类的操作一起使用,并且它还为我提供了诸如/2010/01/08/blogs/1-to_param-etc之类的路由,并且在URL的中间添加了博客。

那么,有没有一个我缺少的聪明解决方案,还是我需要走map.connect路线?

最佳答案

我最近遇到了同样的问题,虽然这可能不是您要查找的内容,但是我已经做了很多工作来解决此问题:

config/routes.rb :

map.entry_permalink 'blog/:year/:month/:day/:slug',
                    :controller => 'blog_entries',
                    :action     => 'show',
                    :year       => /(19|20)\d{2}/,
                    :month      => /[01]?\d/,
                    :day        => /[0-3]?\d/

blog_entries_controller.rb:
def show
  @blog_entry = BlogEntry.find_by_permalink(params[:slug])
end

blog_entries_helper.rb:
def entry_permalink(e)
  d = e.created_at
  entry_permalink_path :year => d.year, :month => d.month, :day => d.day, :slug => e.permalink
end

_entry.html.erb:
<h2><%= link_to(entry.title, entry_permalink(entry)) %></h2>

为了完整起见:

blog_entry.rb:
before_save :create_permalink

#...

private

def create_permalink
  self.permalink = title.to_url
end

#to_url方法来自rsl的Stringex

我本人还是Rails(和编程)的新手,但这可能是实现它的最简单方法。这不是解决问题的RESTful方法,因此不幸的是,您不会获得map.resources的好处。

我不确定(因为我还没有尝试过),但是您可以在application_helper.rb中创建适当的帮助程序,以覆盖blog_path等的默认路由帮助程序。如果可行,那么您将无需更改任何 View 代码。

如果您喜欢冒险,可以查看Routing Filter。我考虑过使用它,但似乎对于完成这项任务来说有些矫kill过正。

另外,如果您不知道,可以执行以下两项操作来从脚本/控制台中测试路由/路径:
rs = ActionController::Routing::Routes
rs.recognize_path '/blog/2010/1/10/entry-title'


app.blog_entry_path(@entry)

祝你好运!

关于ruby-on-rails - 在Rails中做 “/blogs/:year/:month/:day/:permalink”路线的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2030123/

相关文章:

java - 使用 BufferedReader 读取资源

java - 导出后,java无法找到/绘制图像

ruby - Sinatra 路由的必需和可选参数

ruby-on-rails - ruby 的端口

ruby-on-rails - rails : how do you access belongs_to fields in a view?

html - 在 Rails 网络应用程序中,单击链接后样式会发生细微变化

jquery - Rails 3 JQuery page.insert_html 和 TypeError : Element. insert 不是函数

version-control - S3 中的版本控制 Assets /资源,并集成到代码中

asp.net-mvc - 为什么 MvcApplication.RegisterRoutes 定义为静态?

用于查看/修改 IP 路由规则的 Python 接口(interface)