首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未定义方法`build_book_reservation

未定义方法`build_book_reservation
EN

Stack Overflow用户
提问于 2012-04-23 11:15:39
回答 2查看 79关注 0票数 0

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

这是我的应用程序控制器

代码语言:javascript
复制
  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

我想让我们在这里

代码语言:javascript
复制
 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 methodbuild_book_reservation‘以表示0:NilClass`’error

模型/书籍储备b

代码语言:javascript
复制
 belongs_to :reservation

模型/储备库

代码语言:javascript
复制
has_one :book_reservation
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-23 11:53:06

错误的原因是您从未设置会话,但尝试访问应用程序控制器使用的it.In。

代码语言:javascript
复制
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

在你的控制器里

代码语言:javascript
复制
 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。

票数 0
EN

Stack Overflow用户

发布于 2012-04-23 11:28:13

您从来没有将:reservation_id放在会话中。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10279480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档