简体   繁体   中英

Submit form after devise login

I'm trying to let users submit a reservation request without being logged in. After they submit unauthed users are prompted to sign in or sign up. After signing up I'd like the form to be submitted and the (new registered) users to be taken to the checkout page.

Store location keeps the last page to return users after logging in. I need to figure out how to continue users on their intended path by submitting their forms and placing them on the checkout page after sign up/ sign in.

  def store_location
    #stores the last url.  Used for post-login redirects to what the user was trying to do     last.
    if (!request.fullpath.match("/users/") && !request.xhr?) # don't store ajax calls
      session[:previous_url] = request.fullpath
    end
  end

Ok, I think this is pretty dirty but I haven't been able to find another way to do this.

after_sign_in_path_for is a method Devise calls that allows you to send people to different pages after sign in.

I took all the create logic out of the controller and put it into a service object.

  def after_sign_in_path_for(resource)
    if session[:booking_params].present?
      @booking = Booking::CreateBooking.new(user:current_user, params:     session[:booking_params]).return_booking
      checkout_booking_path(@booking.public_id)

    else
      session[:previous_url] || root_path
    end
  end

In the controller, the create method is split into two parts. If there is no current user I save their params into the session and they are sent to login. If there is the CreateBooking service object is called normally.

  def create
    if current_user.nil?
      session[:booking_params] = params
      redirect_to new_user_registration_path
    else
      @booking =  Booking::CreateBooking.new(user:current_user, params:params).return_booking
      respond_to do |format|
        format.html { redirect_to checkout_booking_path(@booking.public_id) }
      end
    end
  end

In the after_sign_in_path_for method I check for the session params and create the booking there.

Let me know if there is a better way to do this!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM