2012-10-02 41 views
0

我目前正在上傳圖片的項目。這些相冊中有用戶,相冊和圖片。我已經達到了以用戶身份創建專輯的程度(尚未完成會話,身份驗證或登錄,但已完成註冊)。我收到一個錯誤我的表單提交Rails所後Rails:ActiveRecord :: RecordNotFound - 無法找到沒有ID的用戶

Couldn't find User without an ID

我發現我的new.html.erb的URL是確定:

http://localhost:3000/users/13/albums/new(沒問題)

但之後我提交它,它給了我一個錯誤,頁面是:

http://localhost:3000/albums/58(問題在URL沒有USER_ID)

沒有人知道爲什麼我的路線突然改變,突然之間以及如何解決它?該錯誤是在我的應用程序/控制器/ albums_controller.rb:14:在'顯示'@user = User.find(params [:user_id])行。

new.html.erb

<%= form_for (@album), url: user_albums_path, :html => { :id => "uploadform", :multipart => true } do |f| %> 
<div> 
    <%= f.label :name %> 
    <%= f.text_field :name %> 


    <%= f.label :description %> 
    <%= f.text_area :description %> 

    <br> 

    <%=f.submit %> 
</div> 
<% end %> 

albums_controller

def show 
    @user = User.find(params[:user_id]) 
    @album = @user.albums.find(params[:id]) 
    @photo = @album.photos.build(params[:photo]) 
    respond_to do |format| 
    if @user.save 
     format.html { redirect_to album_photo_path(@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 update 
end 

def edit 
end 

def create 
    @user = User.find(params[:user_id]) 
    @album = @user.albums.build(params[:album]) 
    respond_to do |format| 
    if @user.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 

路線

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

resources :albums do 
    resources :photos 
end 
+0

你見過這個答案嗎? http://stackoverflow.com/questions/1303980/activerecordrecordnotfound-couldnt-find-user-without-an-id?rq=1 –

+0

是的我已經看到了,但它沒有爲我做任何事情。同樣的錯誤 – Edmund

+0

我認爲問題是我的專輯#重定向創建... – Edmund

回答

0

這是因爲你在創建方法重定向方式。當您執行redirect_to @album時,它使用對象,其狀態和方法來查找要重定向到的正確路徑。例如。如果@album.persisted?和方法是GET,那麼路徑將是album_path。如果沒有堅持,那麼它將是new_album_path

如果您還添加了用戶對象,那麼它將使用正確的ID評估路徑爲user_album_path

format.html { redirect_to [@user, @album], 
       notice: 'Album was successfully created.' } 

此外您的路線可以做得更好。通過指定

resources :albums do 
    resources :photos 
end 

你實際上是宣告了專輯的路線,如「/專輯」,「/專輯/:ID」等,當你已經指定訪問相冊通過嵌套user_album航線資源。無論做什麼surase mentioned in his answer,或者更好,just scope your photos route

scope "/album" do 
    resources :photos 
end 
相關問題