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.
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])
I believe what you want to do is:
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With