Ruby on rails 如何从routes rails填充两次id
我尝试在url中填充两次id,但当我发送参数两次id时,只有一个id填充url id 我的路线:Ruby on rails 如何从routes rails填充两次id,ruby-on-rails,routes,link-to,Ruby On Rails,Routes,Link To,我尝试在url中填充两次id,但当我发送参数两次id时,只有一个id填充url id 我的路线: namespace :admin do resources :stores get "/:id/new_items"=> 'stores#new_items', as: :store_new_items post "/:id/create_items"=> 'stores#create_items', as: :store_create_items get
namespace :admin do
resources :stores
get "/:id/new_items"=> 'stores#new_items', as: :store_new_items
post "/:id/create_items"=> 'stores#create_items', as: :store_create_items
get "/:id/show_items/:id"=> 'stores#show_items', as: :store_show_items
get "/:id/items/:id/new_items_sub" => 'stores#new_items_sub', as: :store_new_items_sub
post "/:id/items/:id/create_items_sub" => 'stores#create_items_sub', as: :store_create_items_sub
get "/:id/items/:id/show_items_sub/:id" => 'stores#show_items_sub', as: :store_show_items_sub
end
我的看法是:
<%= link_to "add new items", admin_store_new_items_sub_path(@store.id, @items.id), :class=> "btn" %>
但我的身份证是这样的:
http://localhost:3000/admin/#{store.id}/items/#{items.id}/new_items_sub
http://localhost:3000/admin/#{store.id}/items/#{store.id}/new_items_sub
请告诉我什么时候我错了?谢谢您的参数应该是唯一的,因此您不能传递多个不同的:id参数。相反您可以执行以下操作:
get '/:store_id/show_items/:id', as: :store_show_items
鉴于:
<%= link_to 'show items', store_show_items_path(@store.id, @item.id) %>
此外,您应该阅读更多关于Rails的内容,在Rails中,可能没有必要通过独立创建每条路线来使您的生活复杂化 您可以对其进行重构,以使用类似这样的嵌套路由。您可能需要更改控制器方法名称:
namespace :admin do
resources :stores do
resources :items, :only => [:new, :create, :show] do
resources :subs, :only => [:new, :create, :show]
end
end
end
这将为您提供如下url帮助:new\u store\u item\u sub_path@store.id,@item.id,用于新操作和存储\u item\u子项_path@store.id,@item.id,@sub.id用于显示操作
运行rake routes以查看您可以访问哪些帮助程序和路由
.您的代码可能会严重干涸。希望这能奏效;可能需要一些调整:
namespace :admin do
resources :stores do
member do
get :new_items, as: :store_new_items
post :create_items, as: :store_create_items
end
get "show_items/:id"=> 'stores#show_items', as: :store_show_items
resources :items do
get :new_items_stub => 'stores#new_items_sub', as: :store_new_items_sub
post :create_items_stub => 'stores#create_items_sub', as: :store_create_items_sub
get "show_items_sub/:id" => 'stores#show_items_sub', as: :store_show_items_sub
end
end
end
用途见2.10和
嵌套资源
问题的关键是您试图两次传递:id参数
幸运的是,Rails以嵌套资源的形式提供了解决方案。这些方法的工作原理是采用父id并在前面加上一个单数前缀,例如:store_id,允许您将:id参数用于另一组方法您必须为此创建一个新的路由。查看 比如说
resources :publishers do
resources :magazines do
resources :photos
end
end
将接受routes/publishers/1/Magazine/2/photos/3看看魔兽世界是否正常运行,谢谢@Nitinjin我能回答这个问题吗:发布看看: