Zephyr4434
Zephyr4434

Reputation: 796

Rails - how to pass created record from the new form to a redirected page

I think this is a pretty simple question but nothing I've read has answered my question directly:

I have a new products page with a standard form. After successfully submitting the form, I redirect to a custom controller action and view called "thanks".

On the "thanks" page, I want to be able to print the name of the product just created and possibly some other attributes.

How do I pass the object just created into my new action? Right now the controller looks like this:

def create
    @product = Product.new(params[:product])
    if @product.save
    flash[:notice] = "Successfully created Product."
    redirect_to thanks_path
    else
    render :action => 'new'
    end
end

def thanks
end

Upvotes: 1

Views: 110

Answers (2)

Brad Werth
Brad Werth

Reputation: 17647

You have two fairly decent options.

First, you could adjust the thanks_path route to take an id parameter, and call it like redirect_to thanks_path(@product). Then you can call it up in your thank you method like any standard show method. It might be worth mentioning that if you are going to be displaying sensitive information on the thank you screen, you may want to use a random uuid, instead of an id, to look up the product.

A better way might be to not redirect at all, but rather adjust your view from simply drawing the form to something like this:

<% if @product && [email protected]_record %>
  THANK YOU MESSAGE GOES HERE
<% else %>
  EXISTING FORM GOES HERE
<% end %>

Upvotes: 2

Billy Chan
Billy Chan

Reputation: 24815

You can't send object through redirect.

There are three ways to solve your problem:

  1. Render the 'thanks' template directly(not action #thanks)

    render 'thanks' # thanks template
    

    You can send whatever instance variable to this template directly. #thanks is no longer needed in this case.

    Drawback: The url won't be changed.

  2. Convey messages through session

    If you want to show certain messages, you can prepare it in #create and send it through session or flash(part of session actually). flash is better as you don't need to clear it manually.

    Note: You may want to use ActiveRecord as session storage if the message size is big, otherwise you'll meet CookiesOverflow by default setting.

  3. Send very simple message through session say obj_id

    Similar to #2 but I thinks this is better than #2. In #thanks, you can construct complex message according to if obj_id is present, what is the id and then find related data through db.

Upvotes: 2

Related Questions