ruby-on-rails – 在Rails中做“/ blogs::year /:month /:da
我有一个博客资源的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的组合来做到这一点,但我有很多通过“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路由? 解决方法
我最近遇到了同样的问题,虽然这可能不是你想要的,但这就是我为照顾它而做的事情:
配置/ 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等的默认路由助手.如果可以,那么您不必更改任何视图代码. 如果您有冒险精神,可以查看Routing Filter.我考虑过使用它,但这项任务似乎有些过分. 此外,如果您不知道,可以执行以下两项操作来测试脚本/控制台中的路径/路径: rs = ActionController::Routing::Routes rs.recognize_path '/blog/2010/1/10/entry-title' 和 app.blog_entry_path(@entry) 祝好运! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |