2012-04-23 117 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