创建到不带 /id 模型的控制器的路由
我有带有外部 collection_id 键的产品,
我想将 id 传递给控制器。 为此,我的控制器有以下路由:
controller :magasin do
get "magasin" => "magasin#index"
end
我的控制器中的唯一视图是 magasin/index.html.erb
到 magasin 的链接是 link_to collection.nom, magasin_path(collection)
这种语法通常适用于带有模型的控制器。这里我的链接是: http://localhost:3000/magasin.2
而不是 http://localhost:3000/magasin/2
稍后我需要调用使用product_kind_id而不是collection_id的相同视图,我将添加按名称/价格排序......
我如何将ID作为普通参数(/:id)
而不是类型(.id
)?
I have product with a foreign collection_id key
I want to pass an id to a controller.
To do so i have the following routes for my controller :
controller :magasin do
get "magasin" => "magasin#index"
end
The only view in my controller is magasin/index.html.erb
The link to magasin is link_to collection.nom, magasin_path(collection)
This kind of syntax usually works in controllers with models. Here my link is : http://localhost:3000/magasin.2
instead of http://localhost:3000/magasin/2
Later on i will need to call the same view with product_kind_id instead of collection_id and i will add sort by name/price ....
How can i have the ID as a normal argument (/:id)
instead of a type(.id
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个流行的 URL 模式是RESTful 路由。 Rails 有这个内置功能,如果您通过railsgeneratescaffoldMagasinnom:string初始化资源,Rails 会为您设置它。
如果您将
resources :magasins
放入路由文件中,它会将/magasins
路由到MagasinsController#index
和/magasins/1< /code> 到
MagasinsController#show
,并将params[:id]
设置为“1”
。它还将设置一些将来有用的其他路由,但目前只会引发“未找到操作”异常。您不想使用点作为参数分隔符,因为 Rails 将点后面的内容放在
request.format
方法中或仅放在params[:format]
中(通常通过生成的脚手架附带的respond_to
方法进行访问)。保存该点以供稍后在提供 XML 和 JSON 等替代显示格式时使用。我意识到我在很小的空间里说了很多,所以一旦您查阅了 Rails Guide 有关该问题的信息,我将非常乐意提供帮助!
A popular URL schema to follow is RESTful routing. Rails has this built-in and will set it up for you if you initialize your resource via
rails generate scaffold Magasin nom:string
.If you put
resources :magasins
in your routing file, it will route/magasins
toMagasinsController#index
and/magasins/1
toMagasinsController#show
withparams[:id]
set to"1"
. It will also set up a few other routes that will be useful in the future but for now will just raise an action not found exception.You don't want to use the dot as an argument delimiter, since Rails places what comes after the dot in the
request.format
method or just inparams[:format]
(ordinarily accessed through therespond_to
method that comes with the generated scaffolds). Save that dot for later when you are working on delivering alternative display formats like XML and JSON.I realize I've said a lot in a small space, so feel free to ask any follow up questions once you've consulted the Rails Guide on the issue, and I'll be very glad to help!