Rails 命名路由和助手 (/controller/:id/randomname)

Rails named route & helper (/controller/:id/randomname)

我正在尝试使以下路由正常工作:

get 'items/:id/pictures' => 'pictures#show'

我应该使用什么样的辅助方法?使用 <%= link_to pictures_item_path do %> 我得到以下错误:

undefined local variable or method `pictures_item_path' for #<#<Class:0x007fa2c6181710>:0x007fa2c40ba7c0>

我已尝试使用 get 'items/:id/pictures' => 'pictures#show', as: 'items/:id/pictures',但出现以下错误:

Invalid route name: 'items_:id_pictures'

你的路线是正确的。如果要使用助手,则必须使用 Named routes.

可以通过传递 :as 选项来命名路由,以便在您的源代码中轻松引用 name_of_route_url 用于完整的 URL 和 name_of_route_path 用于 URI 路径:

# In routes.rb
get '/login', to: 'accounts#login', as: :login

# With render, redirect_to, tests, etc.
redirect_to login_url

希望对您有所帮助。

routes.rb

get 'items/:id/pictures' => 'pictures#show'

在控制台上执行此命令

rake routes

你会得到这样的结果

pictures_item GET    /items/:id/pictures(.:format)   pictures#show

你必须使用pictures_item_path(:id)pictures_item_url(:id)因为它是成员路由

试试这个:

<%= link_to 'item picture', pictures_item_path(@item_id) %>

阅读更多关于 routes