Hoan Dang
Hoan Dang

Reputation: 2280

Confusing in rails routing

I couldn't figure out why this happens after stumbling around Michael Hartl tutorial.

When I click the submit form and expect fail, the expected url after rendering should be '/signup' but some reasons it is '/users'

This is my controller

  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(params[:user])
    if @user.save
      redirect_to @user
    else
      render 'new'
  end

This is my routes

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

First of all when I click the signup link the url is

http://localhost:3000/signup

Then submisson fails this url is

http://localhost:3000/users

Could anyone explain me why it happens ? Thanks

Upvotes: 0

Views: 47

Answers (2)

Chris Heald
Chris Heald

Reputation: 62648

When you are posting to the UsersController (to create a new user, from your signup action), you're invoking the #create action. If you view source on that page, you'll see that the form action is /users and the form method is POST. So when you submit the form, the request made is:

POST /users
(some data)

If the save fails, then your create action there just renders the "new" template. You don't get redirected anywhere. render :action => "new" just renders the template for the new action - it doesn't actually redirect to the new action, or run its action code.

Upvotes: 2

LPD
LPD

Reputation: 2883

According to routes.rb usage in rails, match tag in your routes.rb file determines which controller/action to reach if there is a match.

So here, your signup url is matching to user controller-> new action. But if the new action fails, the url is NOT /signup but user controller's new function instead. So the url displays like that. Hope I made it somewhat clearer.

Upvotes: 0

Related Questions