Redirect Implementation in Ruby on Rails

Rails has ActionController::Base class that implements redirect_to method. This redirect_to method is used for redirection in Rails framework. In order to use redirect_to method, you need to pass URL of another site to it. You can also use it to redirect to another method of another class.

Here is an example that presents with both types of redirects: url and method of another class.

class MyRedirect < ApplicationController
 def index
  redirect_to controller: ‘myredirectclass’, action:’myredirectclassmethod’
 end
 def site_redirect
  redirect_to “http://www.mysite.com”
 end
end

Find it on GitHub

<script src="https://gist.github.com/KMikhaylovCTG/71b496db8bab13fa4465.js"></script>

Note that the body of HTTP redirect is not rendered in the browser. As a result, you don’t need to create views for each of the redirects. There is another important fact about redirect_to. It is ran only after entire action is ran. In other word, it is called after action if finished in its entirety. You can modify this behavior by calling an “and return” inside your redirect set up.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…