url_for 在构建路由时是否使用 to_param

发布于 2024-09-07 18:14:04 字数 757 浏览 1 评论 0原文

在选择要使用的路由时,我无法让 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千寻… 2024-09-14 18:14:04

不确定这是否是预期的行为,但这有效:

map.special ':id/:action', :controller => 'bar', :id => 'special'

而不是

map.special 'special/:action', :controller => 'bar', :id => 'special'

Not sure if this is the expected behavior, but this works:

map.special ':id/:action', :controller => 'bar', :id => 'special'

Instead of

map.special 'special/:action', :controller => 'bar', :id => 'special'
梦断已成空 2024-09-14 18:14:04

是的,将调用 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'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文