我正在试图弄清楚如何指定我尝试使用的路线,但我不断收到路由错误。有人可以指出我哪里出错了,也许可以解释一下更好的办法是什么?
我正在使用这些(嵌套)资源:
resources :users do
resources :playlists
end
型号:
class User < ActiveRecord::Base
has_many :playlists
end
class Playlist < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
end
现在我正在尝试链接到user / show.html.erb文件中的用户播放列表:
<p>
<%= link_to "Playlists", user_playlists_path(@playlist)%></p>
</p>
这使我成功进入播放列表页面(/ users / 1 /播放列表),但当我尝试为此用户添加新的播放列表时,出现以下错误:
Showing /app/views/playlists/_form.html.erb where line #1 raised:
undefined method `playlists_path' for #<#<Class:0x0000000335c688>:0x00000003d0b238>
这是第1行:
<%= form_for(@playlist) do |f| %>
如果这有用的话,这就是rake routes
获得的结果:
Prefix Verb URI Pattern Controller#Action
user_playlists GET /users/:user_id/playlists(.:format) playlists#index
POST /users/:user_id/playlists(.:format) playlists#create
new_user_playlist GET /users/:user_id/playlists/new(.:format) playlists#new
edit_user_playlist GET /users/:user_id/playlists/:id/edit(.:format) playlists#edit
user_playlist GET /users/:user_id/playlists/:id(.:format) playlists#show
PATCH /users/:user_id/playlists/:id(.:format) playlists#update
PUT /users/:user_id/playlists/:id(.:format) playlists#update
DELETE /users/:user_id/playlists/:id(.:format) playlists#destroy
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
root GET / default_pages#home
signup GET /signup(.:format) users#new
signin GET /signin(.:format) users#signin
答案 0 :(得分:2)
错误:
undefined method `playlists_path' for #<#<Class:0x0000000335c688>
和
user_playlist GET /users/:user_id/playlists/:id(.:format)
明确说明您所犯的错误。
<%= form_for(@playlist) do|f| %>
应该是
<%= form_for([@user, @playlist]) do|f| %>
或current_user
,重要的是您需要传递user
对象。
说明:
如果您在update
操作中注意到了(更新后将其重定向到了显示页面),而不是redirect_to user_path(@user)
我们可以只执行redirect_to @user
,Rails会从中推断出您正在重定向到用户的显示路径。
这是类似的情况,类似的情况是,如果您有一个form_for
的播放列表,而您只传递@playlist
而不是[@user, @playlist]
,那么它会尝试查找new_playlist_path
},它不在您的路线中,并会显示错误。
这是关于你如何做的简短gist。
答案 1 :(得分:1)
此:
<%= form_for(@playlist) do |f| %>
应该是这个:
<%= form_for [@user, @playlist] do |f| %>
注意方括号