如何指定命名路由应使用模型的列及其 _url 和 _path 函数?
我有一个带有 id 和 title 列的 Posts 模型。
我的路线(rails 2.3.8)设置如下:
map.post ':title/:id', :controller => 'posts', :action => 'show'
在识别 URL 和显式生成 URL 时,它可以正常工作,就像
post_url(:title => 'foo', :id => 123)
/foo/123 一样。我想要的是能够调用
p = Post.create!(:title => 'foo') # let's assume it gets ID 123
url_for(p)
并获得相同的路径。但我收到错误:
post_url failed to generate from {:action=>"show", :controller=>"posts",
:title=>#<Post id: 123 title: "foo" created_at: ...
如何指定命名路由应使用模型的列及其 _url 和 _path 函数?
I have a Posts model with id and title columns.
I've got my route (rails 2.3.8) set up as follows:
map.post ':title/:id', :controller => 'posts', :action => 'show'
which works correctly when recognising URLs and when generating them explicitly, as in
post_url(:title => 'foo', :id => 123)
which comes out nicely as /foo/123. What I'd like is to be able to call
p = Post.create!(:title => 'foo') # let's assume it gets ID 123
url_for(p)
and get the same path out. But I get an error:
post_url failed to generate from {:action=>"show", :controller=>"posts",
:title=>#<Post id: 123 title: "foo" created_at: ...
How do I specify that a named route should use a model's columns its _url and _path functions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当你声明一个路由时,你调用它的方式需要一定数量的参数,并且必须以正确的顺序指定它们,否则事情可能会变得混乱。
以下是一些典型的路由:
当您想要调用它们时,您需要指定放入路由中的参数,否则它将无效:
您可以在末尾包含可选参数。一般来说,混合和匹配自动路由和手动路由方法是一个坏主意:
括号中的路径参数(如
(:format)
)是可选的,但最好避免这些参数,除非有安全的默认值。通过在路由中包含两个参数而不是简单的
:id
,您可能会导致url_for
方法出错。When you declare a route, the way you call it requires a certain number of parameters, and they must be specified in the correct order or things can get confused.
Here are some typical routes:
When you want to call them, you need to specify the parameters you've put in the route or it will be invalid:
You can include optional parameters at the end. Generally it's a bad idea to mix and match the automatic routing and the manual routing methods:
Path parameters in brackets like
(:format)
are optional but these are best avoided except when there are safe defaults.You're probably tripping up the
url_for
method by including two parameters in your route instead of simply:id
.