0
0
RailsHow-ToBeginner · 3 min read

How to Create a View in Rails: Simple Guide

In Rails, you create a view by adding an HTML template file inside the app/views folder that matches your controller and action name. This file uses embedded Ruby (.html.erb) to display dynamic content when the controller action is called.
📐

Syntax

Rails views are template files stored in app/views/controller_name/. The file name matches the controller action and ends with .html.erb for embedded Ruby HTML templates.

For example, a show action in PostsController uses the view file app/views/posts/show.html.erb.

erb
<!-- File path: app/views/posts/show.html.erb -->
<h1><%= @post.title %></h1>
<p><%= @post.body %></p>
💻

Example

This example shows how to create a simple view for a PostsController with a show action that displays a post's title and body.

ruby+erb
class PostsController < ApplicationController
  def show
    @post = OpenStruct.new(title: "Hello Rails", body: "This is a simple post.")
  end
end

# View file: app/views/posts/show.html.erb
<h1><%= @post.title %></h1>
<p><%= @post.body %></p>
Output
<h1>Hello Rails</h1> <p>This is a simple post.</p>
⚠️

Common Pitfalls

  • Not naming the view file to match the controller action causes Rails to not find the view.
  • Forgetting to set instance variables (like @post) in the controller means the view has no data to display.
  • Placing view files outside the correct app/views/controller_name folder breaks the connection.
erb
<!-- Wrong: view file named incorrectly -->
<!-- File path: app/views/posts/show_post.html.erb -->
<h1><%= @post.title %></h1>

<!-- Right: view file named correctly -->
<!-- File path: app/views/posts/show.html.erb -->
<h1><%= @post.title %></h1>
📊

Quick Reference

ConceptDescription
View file locationapp/views/controller_name/action_name.html.erb
File extension.html.erb for embedded Ruby HTML templates
Controller variableUse instance variables (e.g., @post) to pass data to views
RenderingRails auto-renders view matching controller action unless specified otherwise

Key Takeaways

Create view files inside app/views/controller_name/ matching the action name with .html.erb extension.
Use instance variables in controllers to pass data to views for dynamic content.
Rails automatically renders the view matching the controller action unless told otherwise.
Ensure view file names and locations exactly match controller and action names to avoid errors.
Use embedded Ruby tags <%= %> inside .html.erb files to insert dynamic content.