2012-10-03 27 views
3

嗨我目前正在使用嵌套資源。Rails:未定義的方法`photos_path'?

路線

Pholder::Application.routes.draw do 
resources :users do 
    resources :albums do 
    resources :photos 
    end 
end 
end 

我有3個型號(用戶,相冊,照片)。我已經設法註冊用戶並創建相冊,但我一直試圖爲照片製作表格。在創作的專輯,用戶被重定向到相冊/顯示頁面:

專輯/節目

<% if @album.photos.any? %> 
yes pics 
<% else %> 
no pics 
<% end %> 


<%= link_to "Upload new pics!", new_user_album_photo_path(@user, @album) %> 

,你可以看到,在頁面的底部有新的照片的路徑,這就是問題所在。當我點擊鏈接,它給了我一個錯誤:

undefined method photos_path」爲#<#:在該頁面的行#3時0x007fb69e167220>`

錯誤(照片/新)

照片/新

<% provide(:title, "Upload pictures") %> 

<%= form_for(@photo, :html => { :multipart => true }) do |f| %> 

<%= f.file_field :photo %> 

<% end %> 

我懷疑是我把錯誤的信息傳遞給控制器​​(我仍然在放什麼在控制非常不穩定。)?這是我的照片控制器。

照片控制器

class PhotosController < ApplicationController 

    def new 
     @user = User.find(params[:user_id]) 
     @album = @user.albums.find(params[:album_id]) 
     @photo = @album.photos.build 
    end 

    def create 
     @album = Album.find(params[:album_id]) 
     @photo = @album.photos.build(params[:photo]) 
     respond_to do |format| 
     if @album.save 
      format.html { redirect_to @album, notice: 'Album was successfully created.' } 
      format.json { render json: @album, status: :created, location: @album} 
     else 
      format.html { render action: "new" } 
      format.json { render json: @album.errors, status: :unprocessable_entity } 
     end 
     end 
    end 

    def show 
     @album = Album.find(params[:album_id]) 
     @photos = @album.photos 
    end 


end 

是我的形式不正確的?我很難理解要在控制器中放置什麼,以及錯誤是發生在窗體還是控制器中。謝謝

讓我知道你是否需要任何更多信息。

回答

5

您必須向link_to助手提供父級資源的相同方式,您也必須將其提供給表單。因此,將表格行更改爲:

<%= form_for([@user, @album, @photo], :html => { :multipart => true }) do |f| %> 

..它應該工作!

+0

完美!!!非常感謝。所以對於嵌套資源,當您創建表單時,您必須爲父(?)資源+您所針對的資源製作表單。 – Edmund

2

所以這裏發生了什麼是Rails正在使用一些反射來看待你傳遞給窗體幫助器的對象,而我猜測它只是一個Photo對象。默認情況下,Rails將查找photos_path,因爲這是POST請求通常會針對創建操作的地方。所以它張貼到/照片其中,不幸根據您當前的路線不存在。

如果改變了形式的輔助線:

<%= form_for [@user,@album,@photo], html: { multipart: true} do |f| %> 

,導致其發佈到/用戶/(用戶ID)/專輯/(相冊ID)/照片應創建新照片。

+0

很好的解釋。我現在明白了! – Edmund