Ruby on Rails ActionController Using Views


Example

Assuming the route:

resources :users, only: [:index]

And the controller:

class UsersController < ApplicationController
  def index
    respond_to do |format|
      format.html { render }
    end
  end
end

The view app/users/index.html.erb will be rendered. If the view is:

Hello <strong>World</strong>

The output will be a webpage with the text: "Hello World"

If you want to render a different view, you can use:

render "pages/home"

And the file app/views/pages/home.html.erb will be used instead.

You can pass variables to views using controller instance variables:

class UsersController < ApplicationController
  def index
    @name = "john"

    respond_to do |format|
      format.html { render }
    end
  end
end

And in the file app/views/users/index.html.erb you can use @name:

Hello <strong><%= @name %></strong>

And the output will be: "Hello john"

An important note around the render syntax, you can omit the render syntax entirely, Rails assumes that if you omit it. So:

class UsersController < ApplicationController
  def index
    respond_to do |format|
      format.html { render }
    end
  end
end

Can be written instead as:

class UsersController < ApplicationController
  def index
    respond_to do |format|
      format.html
    end
  end
end

Rails is smart enough to figure out that it must render the file app/views/users/index.html.erb.