问题
I defined nested resources like this
resources :item, :only => [:create, :destroy, :update] do
resources :item_image, :only => [ :new, :create, :show , :destroy, :index]
end
And my routes look like this (output of rake routes)
item_item_image_index GET /item/:item_id/item_image(.:format) item_image#index
POST /item/:item_id/item_image(.:format) item_image#create
new_item_item_image GET /item/:item_id/item_image/new(.:format) item_image#new
item_item_image GET /item/:item_id/item_image/:id(.:format) item_image#show
DELETE /item/:item_id/item_image/:id(.:format) item_image#destroy
I thought the first column of the output is "the named routes".
I want to show a path to /item/:item_id/item_image(.:format) in one of my view.
item_item_image_index GET /item/:item_id/item_image(.:format) item_image#index
I tried this:
<%= link_to "users", item_item_image_index %>
and also this
<%= link_to "users", item_images_path %>
Neither works
I got "undefined local variable or method `item_images_path/item_item_image_index'" error
回答1:
you should try:
<%= link_to "users", item_item_image_index_url(@item) %>
or
<%= link_to "users", item_item_images_url(@item) %>
or
<%= link_to "users", item_item_image_index_path(@item) %>
or
<%= link_to "users", item_item_images_path(@item) %>
don't forget the url needs an :item_id, hence you need to pass an item as an argument.
actually, you should avoid naming that model "ItemImage". An Item has Images, that's what you need to know. you'll get better helper names like "item_images_url"
回答2:
item_item_image_index GET /item/:item_id/item_image(.:format) item_image#index
In this route item_item_image_index
, you need a item_id
in the url
Lets you have an object of Item model named as @item, then your link will be
<%= link_to 'users', item_item_image_index_path(@item) %>
Here You need to append '_path' after the route helper "item_item_image_index
". While passing the @item
variable, it will take the @item.id
as item_id
and completes the URL of the link.
来源:https://stackoverflow.com/questions/18036721/how-to-use-ruby-on-rails-named-routes