问题描述
给定以下资源定义:
map.resources :posts, :except => [:show]
map.post '/:year/:month/:slug, :controller => :posts, :action => :show
我可以使用以下语法让 url_for
为我工作:
I can make url_for
work for me, using this syntax:
<%= link_to @post.title, post_url(:year => '2010', :month => '02', :slug => 'test') %>
但是有没有办法让这个工作?
But is there a way to make this work?
<%= link_to @post.title, @post %>
目前它抛出这个错误:
No route matches {:year=>#<Post id: 1, title: "test", (...)>, :controller=>"posts", :action=>"show"}
显然它将@post 对象传递给第一个路由参数(似乎是 Rails 错误...).但是我可以为我做这件事吗?我要补充一点,搞乱 default_url_options
是一个死胡同.
Apparently it passes the @post object to the first route parameter (seems like a Rails bug...). But can I make this work for me? I'll add that messing with default_url_options
is a dead end.
仅适用于 Rails 3.x 的解决方案是可以的,但我不想使用任何插件.
Solution working only in Rails 3.x is ok, but I would prefer not to use any plugins.
推荐答案
如何为 PostsController
修复 url_for
?可能不是很优雅,但它是干的,事情应该可以正常工作.
How about fixing url_for
for the PostsController
? May not be very elegant but it is DRY and things should just work.
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
protected
def url_for(options = {} )
if options[:year].class.to_s == "Post"
obj = options[:year]
options[:year] = obj.year
options[:month] = obj.month
options[:slug] = obj.slug
end
super(options)
end
end
这篇关于自定义 RESTful 资源的 url_for(复合键;不仅仅是 id)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!