2010-01-08 54 views
6

我有一个博客资源blogs_controller,所以我如下得到了典型的路线现在:在Rails中做“/ blogs /:year /:month /:day /:permalink”路线的最佳方法是什么?

/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路线与博客中的中间URL。

那么,有没有一个聪明的解决方案,我错过了,或者我需要去map.connect路线?

回答

13

我遇到同样的问题,最近,和,虽然这可能不是你要找的内容,这是我做了什么来照顾它:

的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(和编程)还是一个新手,但这可能是最简单的方法。这不是一种REST式的处理事情的方式,因此不幸的是,您无法从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) 

祝你好运!

+0

感谢周杰伦这是一个很好的写法,为我节省了很多时间! – 2010-07-10 20:00:08

+0

真棒解释! – 2010-10-19 03:42:48

+0

该路线的导轨3版本是什么? – sguha 2013-03-15 11:10:04

2

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 “本地主机:3000 /用品/ 2005/11/06” 映射到

params = { :year => '2005', :month => '11', :day => '06' } 

看起来你想做的事同样的事情,但后缀slu suff。您的新链接和编辑链接仍然是“旧学校”链接,如“localhost:3000/articles/1/edit”和“localhost:3000/articles/new”。只是“显示”链接应该用这个更新。

+0

嘿jarrett,感谢您的职位。 slu is是没有问题的,to_param可以照顾到这一点。我真正想做的是摆脱'map.connect',并在'map.resources'的调用中处理这个,所以我不需要修改我现有的所有对blog_path(@blog)的调用等。理想情况下我想打电话给url_for(@blog),然后找回类似'/ blogs/2010/01/08/1-to_param-or-something'的东西,我想这是map.connect所不可能的。我猜我想要的是不可能的(无论如何,这种URL格式RESTful?),我只是想看看是否有人有任何创造性的解决方案。 – carpeliam 2010-01-08 22:34:02

相关问题