好的,另一个恼人的问题。
我有一个使用这样的索引操作的GuestsController:
def index
@booking = Booking.find(session[:booking_id]) #i have also hard coded values to make sure the session isn't the issue
@guest = Guest.find(session[:guest_id])
end
和个人行动(执行更新)如下:
def personal
@guest = Guest.find(session[:guest_id])
if @guest.update(post_params)
redirect_to :controller => 'guests', :action => 'cards'
else
render 'index'
end
end
我的index.html.erb视图使用@booking变量:
<%= @booking.friendly_id %> #this is one example
还包含将“名称”字段提交给个人操作的表单。如果数据有效,它会更新,但如果它无效,则@booking变量不存在???
我需要显示验证错误,因此我不能只使用redirect_to。
我得到的错误是:来宾中的NoMethodError#personal 和未定义的方法`friendly_id'代表nil:NilClass
有什么想法吗?
答案 0 :(得分:1)
只需初始化else部分
中的对象 else
@booking = Booking.find(session[:booking_id])
render 'index'
end
答案 1 :(得分:1)
如何将@booking
和@guest
定义移至before_filter?
before_filter do
@booking = Booking.find(session[:booking_id]) #i have also hard coded values to make sure the session isn't the issue
@guest = Guest.find(session[:guest_id])
end
答案 2 :(得分:0)
当@booking
为nil
时,需要处理一些事情 - 如果我正确地阅读,可能会发生这种情况。
def index
if Booking.find(session[:booking_id])?
@booking = Booking.find(session[:booking_id])
else
@booking = Booking.build #or whatever you want here
end
@guest = Guest.find(session[:guest_id])
end