2013-05-04 28 views
0

我得到一個錯誤說 「爲無未定義的方法`詩句:NilClass」 當我訪問如何解決未定義的方法錯誤與Rails應用程序中的嵌套資源?

/books/1/chapters/1/verses/new 

我的routes.rb:

resources :books do 
    resources :chapters do 
    resources :verses 
    end 
end 

verse_controller.rb:

class VersesController < ApplicationController 
    before_filter :find_book 
    before_filter :find_chapter, :only => [:show, :edit, :update, :destroy] 

    def new 
     @verse = @chapter.verses.build 
    end 


    private 
    def find_book 
     @book = Book.find(params[:book_id]) 
    end 

    def find_chapter 
     @chapter = Chapter.find(params[:chapter_id]) 
    end 

end 

有關如何解決此問題的任何建議?

回答

0

的問題是在你的before_filter

before_filter :find_chapter, :only => [:show, :edit, :update, :destroy] 

現在你打new,但沒有before_filter觸發new,所以@chapter爲零。

解決方案:將:new添加到唯一陣列。

更新您使用參數獲取ids的方式不正確,params用於查詢字符串或POST。您需要額外的努力才能從路徑中獲得參數。

before_filter: get_resources # Replace your two filters 

private 
def get_resources 
    book_id, chapter_id = request.path.split('/')[1, 3] 
    @book = Book.find(book_id) 
    @chapter = Chapter.find(chapter_id) 
end 
+0

當我把參數[:chapter_id],我得到的參數打印。但是當我訪問該頁面時,出現錯誤消息:未知屬性:chapter_id。 – sharataka 2013-05-04 16:39:20

+0

@sharataka,檢查我的更新 – 2013-05-04 17:03:37

相關問題