Rail 3:重定向后实例变量不可用 [英] Rail 3: instance variable not available after redirection

查看:49
本文介绍了Rail 3:重定向后实例变量不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 3 中有一个各种各样的表单向导.基本上,我创建了一个酒店对象,然后当所有这些都完成后,我想为该酒店创建一个位置对象.我用于创建酒店的控制器代码如下所示:

I've a got a form wizard of sorts in Rails 3. Basically, I create a hotel object and then when all of that is complete I want to create a location object for that hotel. My controller code for creating the hotel looks like this:

  def create
    @hotel = Hotel.new(params[:hotel])

    respond_to do |format|
      if @hotel.save
        @location = Location.new
        format.html { redirect_to '/set_location'}
      else
        format.html { render action: "new" }
      end
    end
  end

然后在/set_location"页面中,我有一个用于设置位置的表单.但是,我在 @location 实例变量的 html.erb 上收到 'undefined method model_name for NilClass:Class' 错误.

Then in the '/set_location' page I have a form which sets the location. However, I'm getting an 'undefined method model_name for NilClass:Class' error on the html.erb for the @location instance variable.

这真的很奇怪,因为当我使用 render '/set_location' 而不是 redirect_to 时它工作正常.但是,我想使用redirect_to方法来防止重复记录提交.

This is really strange as when I use render '/set_location' instead of redirect_to then it works fine. However, I want to use the redirect_to method in order to prevent duplicate record submission.

在此先感谢您对此的任何帮助.

Thanks in advance for any help on this.

推荐答案

HTTP 在设计上是无状态的.如果您想在请求之间共享状态(重定向到另一个请求),您应该使用 session 哈希.像这样:

HTTP is stateless by design. If you want to share the state between requests (redirect leads to another request) you should use the session hash. Like this:

session[:hotel_id] = @hotel.id

然后你通过这种方式在 /set_location 中检索你的 Hotel:

And then you retrieve your Hotel in the /set_location this way:

Hotel.find(session[:hotel_id])

这篇关于Rail 3:重定向后实例变量不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆