Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rail 3: instance variable not available after redirection

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

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.

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.

like image 490
Gerard Avatar asked Apr 11 '12 11:04

Gerard


2 Answers

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

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

Hotel.find(session[:hotel_id])
like image 145
jdoe Avatar answered Nov 06 '22 01:11

jdoe


I believe what you want to do is:

  1. Identify which controller and action responds to the "/set_location" request.
  2. There you will see that you are missing this line @location = Location.new. You need to create it there.

Instance variables in Rails are often used to pass information between your controller and your view, and that is why when doing render, you don't get that error. Rails views know about instance variables from controllers.

However, you are doing a redirect, and therefore you are calling another controller which has no idea what @location is.

like image 44
Nobita Avatar answered Nov 06 '22 01:11

Nobita