3

In my Rails app (with devise authentication) anyone can start creating a post, but if not signed in when they hit save/create/post they first have to create a user name or login = perfect.

My code:

 before_filter :authenticate_user!, :except => [:show, :index, :new, :edit]

Sadly once they signed in it either redirects to the index page or back to the post, but everything is gone and subsequently the user has to start over again.

How can I change the redirect and also how can I stop the post from being lost after login again?

I know its something to do with:

  def after_sign_up_path_for(resource)
  new_user_confirmation_path
  end
Erin Walker
  • 739
  • 1
  • 11
  • 30
  • The Devise wiki has the following for redirecting back: https://github.com/plataformatec/devise/wiki/How-To:-Redirect-back-to-current-page-after-sign-in,-sign-out,-sign-up,-update I would guess you need to store the text in some sort of session variable, but I am not sure. – dewyze Mar 30 '13 at 21:50

1 Answers1

1

HTTP is stateless - post parameters (as well as all other parameters) are only valid for one request. Basically, there is no way for http to know what parameters were transmitted before the redirect.

This is where sessions might come in handy - you can do something like this in your controller to solve both your problems.

before_filter :authenticate_user!, :except => [:show, :index, :new, :edit, :create]
# include create action inside except hash

def create
  if !user_signed_in? # check whether user is logged in manually
    session[:post] = params[:post] # assign post data to session if not
    redirect_to new_user_session_path
  else
    # ...
  end
end

With that session, http becomes "stateful" since your session hash is available throughout several requests (until you destroy it).

And then, when the user has logged in, use the session inside your form to pre-populate the form fields.

Community
  • 1
  • 1
Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115