Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using redirect_to with a specific ActiveRecord object to create a link to that object

I'm going through Michael Hartl's tutorial at http://ruby.railstutorial.org/. It's basically a message board app where Users can post Messages and others can leave Replies. Right now I'm creating Users. Inside the UsersController things look like this:

    class UsersController < ApplicationController
      def new
        @user = User.new
      end

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

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

The author says that the following lines are equivalent. Which makes sense to me:

    @user = User.new(params[:user])
    is equivalent to
    @user = User.new(name: "Foo Bar", email: "foo@invalid",
             password: "foo", password_confirmation: "bar")

redirect_to @user redirects to show.html.erb. How exactly does that work? How does it know to go to show.html.erb?

like image 713
Mike Glaz Avatar asked May 07 '12 01:05

Mike Glaz


1 Answers

This is all handled through the magic of Rail's restful routing. Specifically, there's a convention that doing a redirect_to a specific object goes to the show page for that object. Rails knows that @user is an active record object, so it interprets that as knowing you want to go to the show page for the object.

Here's some detail from the appropriate section of the Rails Guide - Rails Routing from the Outside In.:

# If you wanted to link to just a magazine, you could leave out the
# Array:

<%= link_to "Magazine details", @magazine %>

# This allows you to treat instances of your models as URLs, and is a
# key advantage to using the resourceful style.

Basically, using restful resources in your routes.rb file gives you 'shortcuts' for creating url's directly out of ActiveRecord objects.

like image 94
Kevin Bedell Avatar answered Oct 30 '22 05:10

Kevin Bedell