url_for 在构建路由时是否使用 to_param
在选择要使用的路由时,我无法让 url_for 渲染考虑到 to_param 。
我有两组使用相同模型(Foo)的路线。如果 Foo.is_special,则 url 应映射到 /special/:action。如果不是,它应该映射到 /:id/:action。因为它是相同的模型,所以我希望 url_for 自动知道要映射到哪个路径,具体取决于 is_special。
routes.rb:
map.special 'special/:action', :controller => 'bar', :id => 'special'
map.regular ':id/:action', :controller => 'bar', :id => /\d+/
foo.rb:
def to_param
is_special ? 'special' : id.to_s
end
当我显式设置 :id 时,这有效。例如:
url_for(:controller => 'bar', :id => 'special')
url_for(:controller => 'bar', :id => @foo)
当 :id 显式设置为 'special' 且 @foo is_special == false 时,为特殊生成正确的 url。但是,当 @foo.is_special == true 时,特殊路由无法识别。
I'm having trouble getting url_for to render take to_param into account when choosing which route to use.
I have two sets of routes that use the same model (Foo). If Foo.is_special, the url should map to /special/:action. If it isn't, it should map to /:id/:action. Because it's the same model, I'd like url_for to automatically know which path to map to, depending on is_special.
routes.rb:
map.special 'special/:action', :controller => 'bar', :id => 'special'
map.regular ':id/:action', :controller => 'bar', :id => /\d+/
foo.rb:
def to_param
is_special ? 'special' : id.to_s
end
This works when I set :id explicitly. For example:
url_for(:controller => 'bar', :id => 'special')
url_for(:controller => 'bar', :id => @foo)
Generates the correct url for special when :id is set explicitly to 'special', and when @foo is_special == false. However, when @foo.is_special == true, the special route isn't recognized.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不确定这是否是预期的行为,但这有效:
而不是
Not sure if this is the expected behavior, but this works:
Instead of
是的,将调用 to_param 将 @foo 转换为字符串。你确定它没有被调用吗?也许问题出在其他地方。在控制台中尝试一下以确保。要在控制台中测试路由,您可以首先输入
include ActionController::UrlWriter; default_url_options[:host] = 'localhost:3000'
Yes, to_param will be called to translate @foo into a string. Are you sure that it isn't being called? Maybe the problem is somewhere else. Try it in the console to make sure. To test routes in the console you can first enter
include ActionController::UrlWriter; default_url_options[:host] = 'localhost:3000'