我有一个带有博客资源的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}/}但我不确定这是如何处理像“新建”或“创建”这样的动作的,而且它也给了我一个像/2010/01/08/blogs/1-to_param-etc这样的路径,在网址中间有博客。
那么,我有没有一个聪明的解决方案,或者我需要走map.connect路线呢?
发布于 2010-01-10 13:59:48
我最近遇到了同样的问题,虽然这可能不是你想要的,但以下是我为解决这个问题所做的:
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])
endblog_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)祝好运!
发布于 2010-01-09 03:59:16
从API Docs
map.connect 'articles/:year/:month/:day',
:controller => 'articles',
:action => 'find_by_date',
:year => /\d{4}/,
:month => /\d{1,2}/,
:day => /\d{1,2}/使用上面的路由,URL "localhost:3000/articles/2005/11/06“映射到
params = { :year => '2005', :month => '11', :day => '06' }看起来你想做同样的事情,但是后缀是post slug。您的新链接和编辑链接仍然是“老式”链接,如"localhost:3000/articles/1/ edit“和"localhost:3000/articles/ new”。只有"show“链接应该用这个更新。
https://stackoverflow.com/questions/2030123
复制相似问题