form_form 和 path_prefix 中的自定义参数
我有这条路线:
# config/routes.rb
map.namespace :backshop, :path_prefix => '/:shop_id/admin' do |backshop|
backshop.resources :items
end
我想使用 form_for 魔法在以下两个视图上重用相同的表单:new 和 edit 视图:
<% form_for [:backshop, @item] do |f| %>
这用于有效,并用于根据 @item 对象的状态构建创建项目的 url 或更新项目的 url。
但这在这种情况下不起作用,因为没有 shop_id 参数,路由就不存在,而且我不知道如何对 form_for 说这样的话:
<% form_for [:backshop, @item], :shop_id => @shop do |f| %>
因为它尝试像 :shop_id 参数一样使用 @item 。
或者像这样
<% form_for [:backshop, @shop, @item] do |f| %>
因为它尝试构建这个网址:
backshop_shop_order_path
我知道我可以从部分中提取 form_for 声明,并根据 new 或 进行不同的调用编辑:
<% form_for( @item, :url => backshop_items_path( @shop ) ) do |f| %>
但
<% form_for( @item, :url => backshop_item_path( @shop, @item ) ) do |f| %>
我只是想不要这样做,因为我有一堆模型,而且有点无聊:)
感谢
您的任何建议。
I have this route:
# config/routes.rb
map.namespace :backshop, :path_prefix => '/:shop_id/admin' do |backshop|
backshop.resources :items
end
And I want to use the form_for magic to reuse the same form on both: new and edit views:
<% form_for [:backshop, @item] do |f| %>
This used to works, and used to build a create url for the item or update url for the item depending on the status of the @item object.
But this is not working on this case because the routes don't exists without the shop_id parameter, and I don't know how to say to the form_for something like this:
<% form_for [:backshop, @item], :shop_id => @shop do |f| %>
Because it tries to use the @item like the :shop_id parameter.
Or like this
<% form_for [:backshop, @shop, @item] do |f| %>
Because it tries to build this url:
backshop_shop_order_path
I Know I can just to extract the form_for declaration from the partial and do different calls on depending if new or edit:
<% form_for( @item, :url => backshop_items_path( @shop ) ) do |f| %>
and
<% form_for( @item, :url => backshop_item_path( @shop, @item ) ) do |f| %>
But I just wanted don't do this because I have a bunch of models and is a few boring :)
Thanks for any suggestion
f.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您想使用名称空间进行嵌套资源,也许您可以将路线重写为类似
现在您应该能够使用
[@shop, @item]
来获取您想要的路线。使用rake paths
来检查路由并看看它们是否符合您的喜好。Looks like you want to do nested resources with a namespace maybe you can rewrite your routes to something like
Now you should be able to use
[@shop, @item]
to get the route you want. Userake routes
to examine the routes and see if they are to your liking.