Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When the form is submitted with an error, the rendered url changes in Rails 4

I have created a user signup page. When the user submits the form incorrectly, when displaying a validation error, it does not render on the same URL.

The signup form is located at this url:

http://localhost:3000/signup

I have added the following routes for the signup page:

resources :users
match '/signup',  to: 'users#new', via: 'get'

When I submit the form, the model validation shows up but the url redirects to:

http://localhost:3000/users

I want the user to remain at the same url after submitting the form.

http://localhost:3000/signup

This is my controller code:

def new
    @user = User.new
  end

  def create

    @user = User.new(user_params) # Not the final implementation!

    if @user.save
      # Handle a successful save.
    else
        render 'new'
    end
  end

This is the beginning tag of my form:

<%= form_for @user, url: {action: "create"}  do |f| %>
like image 846
Jaskaran Avatar asked May 14 '14 16:05

Jaskaran


1 Answers

I'm working with Rails 5, but I suspect it's not too different conceptually.

In routes.rb:

get 'signup', to: 'users#new'
post 'signup', to: 'users#create'
resources :users

and in your form helper:

<%= form_for @user, url: signup_path  do |f| %>

Essentially, the reason why it's not working as described in your original post is because when the form posts (rails 4.2 form helpers), it's tied to url: {action: "create"}, which by default, according to the routes automatically generated for resources :users, is post '/users', to: 'users#create (rails 4.2 routing guide). And by searching top down in routes.rb, it'll see this first and you end up with http://localhost:3000/users.

So, the changes I propose, should bind the form to post to the signup path instead which, in routes.rb, is seen as the second route entry.

like image 136
solstice333 Avatar answered Sep 29 '22 09:09

solstice333