实例变量未在控制器中获取
Instance variables not picked up in controller
我有一个 GamesController,它有一个 success 方法。该方法应该使用提供的参数找到(游戏)预订对象,并允许视图显示与预订对象相关的信息。这样做会报错,提示 @booking 实例变量为 Nil。我的设置如下:
游戏控制器
class GamesController < ApplicationController
def success
@booking = Booking.find_by(session_id: params[:session_id])
end
end
success.html.erb
<h1>Booking reference: <%= @booking.reference %></h1>
<p>Thank you for your booking</p>
我可以通过创建一个单独的方法 set_booking 来解决这个问题,该方法找到预订并通过之前的操作将其传递给成功函数.我修改后的设置是:
游戏控制器
class GamesController < ApplicationController
before_action :set_booking, :only => [ :success ]
def success
end
def set_booking
@booking = Booking.find_by(session_id: params[:session_id])
end
end
success.html.erb(不变)
<h1>Booking reference: <%= @booking.reference %></h1>
<p>Thank you for your booking</p>
我的问题:我不明白的是,为什么预订对象在没有before_action的视图中不可用。我认为使用“@”将其设为实例变量就足够了 - 是否有我在这里缺少的约定?
谢谢!
感谢大家的反馈。
我对这种行为感到非常困惑,所以我重写了控制器(是的,它被压缩以使其更清晰)。然后它起作用了——但我并不完全满意,因为我找不到错字。简而言之,没有错字,而是 success 函数被定义了两次 ♂️ 很高兴终于弄明白了
我有一个 GamesController,它有一个 success 方法。该方法应该使用提供的参数找到(游戏)预订对象,并允许视图显示与预订对象相关的信息。这样做会报错,提示 @booking 实例变量为 Nil。我的设置如下:
游戏控制器
class GamesController < ApplicationController
def success
@booking = Booking.find_by(session_id: params[:session_id])
end
end
success.html.erb
<h1>Booking reference: <%= @booking.reference %></h1>
<p>Thank you for your booking</p>
我可以通过创建一个单独的方法 set_booking 来解决这个问题,该方法找到预订并通过之前的操作将其传递给成功函数.我修改后的设置是:
游戏控制器
class GamesController < ApplicationController
before_action :set_booking, :only => [ :success ]
def success
end
def set_booking
@booking = Booking.find_by(session_id: params[:session_id])
end
end
success.html.erb(不变)
<h1>Booking reference: <%= @booking.reference %></h1>
<p>Thank you for your booking</p>
我的问题:我不明白的是,为什么预订对象在没有before_action的视图中不可用。我认为使用“@”将其设为实例变量就足够了 - 是否有我在这里缺少的约定?
谢谢!
感谢大家的反馈。
我对这种行为感到非常困惑,所以我重写了控制器(是的,它被压缩以使其更清晰)。然后它起作用了——但我并不完全满意,因为我找不到错字。简而言之,没有错字,而是 success 函数被定义了两次 ♂️ 很高兴终于弄明白了