2012-04-23 113 views
0

嗨我只是想知道,如果,爲什麼會找不到刷新時我的預訂,並在其他控制器未定義的方法`build_book_reservation

用它,這是我的ApplicationController

helper :all # include all helpers, all the time 


    private 
def current_reservation 
    @reservation ||= Reservation.find(session[:reservation_id]) if session[:reservation_id] 
    #last assigned value will be returned as default. 
end 

def create_reservation_session(id) 
    session[:reservation_id] = id 
end 

def destroy_reservation_session 
    session[:reservation_id] = nil 
end 

和我在這裏想給我們這

def new 
    @book_reservation = BookReservation.new 
end 

def create 
    @reservation = current_reservation 
    @[email protected]_book_reservation(params[:book_reservation]) 
    if @book_reservation.save 
    #If success set session 
    create_reservation_session(@reservation.id) 
    #redirect_to root_url, :notice => "Successfully created book reservation." 
    else 
    render :action => 'new' 
    end 
end 

它提出undefined method build_book_reservation」的零:NilClass`錯誤


模型/ book_reservation.rb

belongs_to :reservation 

模型/ reservation.rb

has_one :book_reservation 

回答

0

錯誤的原因是你從來沒有設置會議,但您嘗試訪問it.In您的應用程序控制器使用

private 
def current_reservation 
    @reservation ||= Reservation.find(session[:reservation_id]) if session[:reservation_id] 
    #last assigned value will be returned as default. 
end 

def create_reservation_session(id) 
    session[:reservation_id] = id 
end 

def destroy_reservation_session 
    session[:reservation_id] = nil 
end 

在你的控制器

def new 
    @book_reservation = BookReservation.new 
end 

def create 
    @reservation = Reservation.find(params[:reservation_id]) 
    if @reservation 
    @[email protected]_book_reservation(params[:book_reservation]) 
    if @book_reservation.save 
     #If success set session 
     create_reservation_session(@reservation.id) 
     #redirect_to root_url, :notice => "Successfully created book reservation." 
    else 
     render :action => 'new' 
    end 
    else 
     render :action => 'new' 
    end 

然後,每當你需要,你可以使用current_reservation 。

+0

嗨試過你的建議,它現在工作它引發不同的錯誤'未定義的方法'build_book_reservation'爲零:NilClass'這可能是一個主題只是想知道如果你知道爲什麼發生這種情況只是編輯我的職位,在此先感謝:) – Led 2012-04-23 12:09:03

+0

在您的創建方法中添加@reservation並告訴我您獲得了什麼輸出? – 2012-04-23 12:15:48

+0

怎麼樣放一個日誌?對不起im新的紅寶石:( – Led 2012-04-23 12:17:25

0

你永遠不要把:reservation_id了會議。

這意味着session[:reservation_id]nilReservation.find(nil)引發了您所看到的異常。

+0

呃這是你的意思? 'reservation = Reservation.find(session [:reservation_id])'對不起,我正在學習我的啞巴 – Led 2012-04-23 11:33:37

+0

是的,就是那個。我編輯了答案,嘗試更清晰。 – Sionide21 2012-04-23 11:40:10

+0

感謝只是一個後續問題,我只是編輯我的帖子我做對了嗎? – Led 2012-04-23 11:47:21