Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Redirect Not Going as HTML

I have a sign up form that should redirect the user to their profile if sign up is successful. If registration fails I want to put up an error message without reloading the page using Javascript.

Here's my form header:

<%= form_for resource, as: resource_name, url: registration_path(resource_name), remote: true do |f| %>

My registration controller:

def create
  respond_to do |format|
    if resource.saved
      sign_up(resource_name, resource)
      format.html { redirect_to current_employer }
    else
      format.js { render 'employers/sign_up_failure' }
    end
  end
end

So the failure works. It displays an error message above the form without reloading the page. The successful registration format.html { redirect_to current_employer } is not working.

My server log says the redirect was handled:

Redirected to http://localhost:3000/employers/27

But it looks like the show action on my Employers controller is being called as Javascript:

Processing by EmployersController#show as JS

So when I submit the form, it does not redirect me to my profile page. The page doesn't flicker. I am logged in though, so if I refresh the page it shows that I am logged in.

BTW, I am using Devise and my Registration controller is an amendment to what Devise uses.

Not sure why this isn't working. I've taken out the format.js {} part and it still sends the GET call to my Employers#Show action via JS. What I'd like is for the redirect to be formatted as HTML and take me to the profile page.

Any ideas?

SOLUTION Thank you for you help. Face palm, I totally forgot about how remote: true works. Here is my implemented solution... hopefully someone finds this useful.

def create
  respond_to do |format|
    if resource.saved
      sign_up(resource_name, resource)
      #CHANGED
      format.js { render js: "window.location.href = '/#{resource_name}s/#{resource.id}'" }
    else
      format.js { render "#{resource_name}s/sign_up_failure" }
    end
  end
end

This also improved the reusability of the code.

like image 694
Hunter Avatar asked Jun 04 '14 13:06

Hunter


1 Answers

Because you have remote: true on the form it is submitted via ajax, you haven't said what to do if submitted via ajax and successful. The format requested is js not html which is why the redirect isn't working.

You'll need to create a create.js.erb file to serve if successful, handling the redirect through javascript with window.location = "wherever you want to go"

like image 110
j-dexx Avatar answered Sep 19 '22 19:09

j-dexx