0

嗨,我只是想知道为什么会话在刷新时找不到我的预订并在其他控制器中使用它

这是我的应用程序控制器

  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
  @book_reservation=@reservation.build_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为 nil:NilClass` 错误引发 build_book_reservation'


模型/book_reservation.rb

 belongs_to :reservation

模型/reservation.rb

has_one :book_reservation
4

2 回答 2

0

你从来没有参加:reservation_id过会议。

这意味着这session[:reservation_id]nilReservation.find(nil)引发了您所看到的异常。

于 2012-04-23T11:28:13.617 回答
0

错误的原因是您从未设置会话但您尝试访问它。在您的应用程序控制器中使用

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
    @book_reservation=@reservation.build_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。

于 2012-04-23T11:53:06.267 回答