car*_*iam 6 resources routing ruby-on-rails
我有一个博客资源的blogs_controller,所以我现在有了你的典型路线如下:
/blogs/new
/blogs/1
/blogs/1/edit #etc
Run Code Online (Sandbox Code Playgroud)
但这就是我想要的:
/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?
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过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}/}
Run Code Online (Sandbox Code Playgroud)
但是我不确定它如何与"新"或"创建"等行为一起工作,它也给了我一条路径,就像/2010/01/08/blogs/1-to_param-etcURL中间的博客一样.
那么,有一个我缺少的聪明解决方案,还是我需要去map.connect路由?
Jay*_*oza 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/
Run Code Online (Sandbox Code Playgroud)
blog_entries_controller.rb:
def show
@blog_entry = BlogEntry.find_by_permalink(params[:slug])
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
_entry.html.erb:
<h2><%= link_to(entry.title, entry_permalink(entry)) %></h2>
Run Code Online (Sandbox Code Playgroud)
为了完整起见:
blog_entry.rb:
before_save :create_permalink
#...
private
def create_permalink
self.permalink = title.to_url
end
Run Code Online (Sandbox Code Playgroud)
#to_url方法来自rsl的Stringex.
我自己仍然是Rails(和编程)的新手,但这可能是最简单的方法.这不是一种RESTful方式来处理事情,所以不幸的是你没有从map.resources中获益.
我不确定(因为我没有尝试过),但你可以创建适当的助手application_helper.rb来覆盖blog_path等的默认路由助手.如果可以,那么您不必更改任何视图代码.
如果您有冒险精神,可以查看路由过滤器.我考虑过使用它,但对于这项任务来说似乎有些过分.
此外,如果您不知道,可以执行以下两项操作来测试脚本/控制台中的路径/路径:
rs = ActionController::Routing::Routes
rs.recognize_path '/blog/2010/1/10/entry-title'
Run Code Online (Sandbox Code Playgroud)
和
app.blog_entry_path(@entry)
Run Code Online (Sandbox Code Playgroud)
祝好运!
| 归档时间: |
|
| 查看次数: |
2354 次 |
| 最近记录: |