Search code examples
ruby-on-railshttp-redirectruby-on-rails-4rails-activerecordinstance-variables

why does redirecting with an instance variable take you to a show view(Log-in)


How does the following piece of code redirect_to @userin my create action know how to redirect to my show view?

I don't get how it would possibly know this. I know this is a newb question but I just can't understand why @user works. It would make sense if it was something like redirect 'show' but why is @user used?

Here is my controller code:

class UsersController < ApplicationController

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

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)   
    if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end
end

Solution

  • redirect_to @user
    

    is the short hand for:

    redirect_to user_path(@user)
    

    You can either use the long-hand or the short-hand. They will both work the same way.

    by convention, redirect_to @user maps to:

    GET  /users/:id(.:format)    users#show 
    

    That's how it knows to redirect you to the show page.

    The show action is the only one (to my knowledge) that has a short-cut.

    If you do rake routes, you'll see the complete map:

    user_path    GET     /users/:id(.:format)    users#show