Open In App

How to Create Button in Ruby on Rails?

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Ruby on Rails, commonly known as Rails, is a popular web application framework written in the Ruby programming language. It follows the Model-View-Controller (MVC) architectural pattern, which separates the application’s data, logic, and user interface components. Rails emphasizes convention over configuration, which means it provides sensible defaults for getting started quickly without having to configure every aspect of the application.

Create a Demo Project

Before proceeding to the steps, make sure Ruby on Rails is installed on the system.

Step 1: Open the rails terminal, if you’re using Windows the terminal name will be ‘Ubuntu(WSL)’. Now run the following command. It will create a default project named ‘myapp’ in the current directory.

rails new myapp

Screenshot-(48)-modified

;:rails new myapp

Step 2: Use this command to get into your project directory.

cd myapp

Screenshot-(49)-modified

cd myapp

Step 3: Execute the below command in the terminal. It will create a controller file (home_controller.rb) in ‘app/controllers’ and corresponding view file (index.html.erb) which is our webpage in ‘app/views/home’. It will also create a route in ‘app/config/routes.rb’ which is needed for every webpage.

rails generate controller home index

Screenshot-(50)-modified

rails generate controller home index

Step 4: Initially, when running the server, it gives the default welcome page as output. To display our home page, make changes in the ‘app/config/routes.rb’ file. Adding the following line in the file will set our home page as root.

root ‘home#index’

Screenshot-(51)-modified

Set the home as root

Step 5: Run the server using the command below and view the output at ‘http://localhost:3000/’. You can also view the default web page if you don’t make any change in ‘routes.rb’.

rails server

Screenshot-(52)-modified

rails server

Output:

Open the browser and paste the link ‘http://localhost:3000/’.

Untitled-design-(4)-modified

index.html.erb output

Creating Buttons in Ruby on Rails

Method 1: Using HTML

You can create buttons using HTML ‘<button>‘ or ‘<input>’ elements directly within your Rails views. For example,

<button type=”button”>Click Me</button>

<input type=”submit” value=”Submit”>

The code given below creates a button called “Click Me” and prints “You clicked the button” when it is clicked. Use this code in ‘index.html.erb’ file and run the ‘rails server’ command.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Demo</title>
</head>
<body>
  <button id="clickButton">Click Me</button>
  <div id="output"></div>

  <script>
    document.getElementById('clickButton').addEventListener('click', function() {
      document.getElementById('output').innerText = 'You clicked the button';
    });
  </script>
</body>
</html>

Output:

HTML-button

HTML Button

Method 2: Using Rails ‘button_to’ helper

button_to’ is primarily used to create buttons that submit forms in Ruby on Rails applications. It is used when you need a button to perform an action that requires form submission, such as submitting data to a controller action. For example,

<%= button_to “Delete”, some_path, method: :delete, class: “btn” %>

Step 1: Open your home_controller file ‘(app/controllers/pages_controller.rb)’ and add the following action:

Ruby
class HomeController < ApplicationController
  def index
    @response = flash[:response]
  end

  def handle_click
    flash[:response] = "You clicked the button"
    redirect_to root_path
  end
end

Step 2: Open the ‘app/views/home’ directory and add the following content to ‘index.html.erb’

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Demo</title>
</head>
<body>
  <%= button_to "Click me", "/home/handle_click", method: :post %>

  <% if @response.present? %>
    <p><%= @response %></p>
  <% end %>
</body>
</html>

This code will generate a button labeled “Click Me”. When clicked, it will submit a POST request to the ‘handle_click’ action asynchronously.

Step 3: In your ‘routes.rb’ file, use the ‘post’ method to define a route for ‘handle_click’ action. Use ‘rails server’ at the end.

post ‘home/handle_click’

Output:

button_to-method

button_to method

Method 3: Using Rails ‘button_tag’ helper

‘button_tag’ is used when you need to create a custom button for UI interactions or other client-side actions that don’t involve form submission. It works as a standalone button. For example,

<%= button_tag “Click me”, class: “btn” %>

Step 1: Open your home_controller file ‘(app/controllers/pages_controller.rb)’ and write the below code:

Ruby
class HomeController < ApplicationController
  def index
  end
end

Step 2: Open the ‘app/views/home’ directory and add the following content to ‘index.html.erb’.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Demo</title>
</head>
<body>
  <%= button_tag "Click Me", id: "clickButton" %>

  <div id="displayText"></div>  

  <script>
    document.getElementById("clickButton").addEventListener("click", function() {
      document.getElementById("displayText").innerText = "You clicked the button";
    });
  </script>
</body>
</html>

Step 3: Your ‘routes.rb’ file in ‘config’ directory should look like this.

Ruby
Rails.application.routes.draw do
  get 'home/index' # Route for the home page
  root 'home#index' # Root route
end

Output:

HTML-button

button_tag method

Method 4: Using Rails ‘link_to’ helper

The ‘link_to’ method is used to generate HTML links (<a> tags) within your views. It’s a helper method provided by Rails to simplify the process of creating links to other pages or resources within your application. For example,

<%= link_to “Link Text”, “path_to_destination” %>

Step 1: Open the ‘app/views/home’ directory and add a ‘link_to’ button in ‘index.html.erb’ with the path to another page.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Demo</title>
</head>
<body>
  <%= link_to "Click Me", clicked_path %>
</body>
</html>

Step 2: Create the new page in ‘app/views/home’ with the name ‘clicked.html.erb’ where the button will navigate.

HTML
<h1>You clicked the link</h1>

Step 3: Create the controller action for new page in ‘home_controller.rb’.

Ruby
class HomeController < ApplicationController
  def index
  end
  
  def clicked
  end
end

Step 4: Finally define the route and run the server using ‘rails server’.

Ruby
Rails.application.routes.draw do
  root 'home#index'
  get 'clicked', to: 'home#clicked'
end

Output:

link_to-method

lint_to method

Method 5: Using Rails ‘form_tag’ helper

The ‘form_tag’ helper is used to create a form without binding it to any specific model object. It generates a basic HTML form element and allows you to define form fields manually. For example,

<%= form_tag some_path do %>

<%= text_field_tag :username %>

<%= password_field_tag :password %>

<%= submit_tag “Submit” %>

<% end %>

Step 1: Open the ‘app/views/home’ directory and add the below content in ‘index.html.erb’.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Demo</title>
</head>
<body>
  <%= form_tag submit_path do %>
    <%= label_tag :username, "Username:" %>
    <%= text_field_tag :username %><br>

    <%= label_tag :password, "Password:" %>
    <%= password_field_tag :password %><br>

    <%= submit_tag "Submit", class: "btn btn-primary" %>
  <% end %>
</body>
</html>

Step 2: Create the new page in ‘app/views/home’ with the name ‘submit.html.erb’ where the button will navigate and heading will display for successful form submission.

HTML
<!DOCTYPE html>
<html>
<head>
  <title>Submission Successful</title>
</head>
<body>
  <h1>Submitted Successfully</h1>
</body>
</html>

Step 3: Create the controller action for new page in ‘home_controller.rb’.

Ruby
class HomeController < ApplicationController
  def index
  end
  
  def submit
  end

  def submit_form
    redirect_to submit_path
  end
end

Step 4: Finally define the route and run the server using ‘rails server’.

Ruby
Rails.application.routes.draw do
  root 'home#index'
  get 'submit', to: 'home#submit', as: 'submit'
  post 'submit', to: 'home#submit_form'
end

Output:

form_tag

form_tag method

Method 6: Using Rails ‘form_for’ helper

The ‘form_for’ helper is used when you want to create a form that is associated with a specific model object. It generates form fields based on the attributes of the model object. For example,

<%= form_for @user do |f| %>

<%= f.text_field :username %>

<%= f.password_field :password %>

<%= f.submit “Submit” %>

<% end %>

Step 1: Change the code in ‘index.html.erb’ as follows:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Button Demo</title>
</head>
<body>
  <%= form_for :user, url: submit_path do |f| %>
    <div class="field">
      <%= f.label :username, "Username:" %>
      <%= f.text_field :username %>
    </div>

    <div class="field">
      <%= f.label :password, "Password:" %>
      <%= f.password_field :password %>
    </div>

    <%= f.submit "Submit", class: "btn btn-primary" %>
  <% end %>
</body>
</html>

The rest of the code will remain as it is. In this code, :user is a symbol representing the model object. When ‘form_for’ is used with a symbol like :user, Rails will generate form fields based on the attributes of the model object represented by that symbol.

Output:

form_tag

form_for method

Regardless of the method chosen, it’s essential to consider usability and accessibility when designing buttons in Rails applications. Buttons should have clear labels, appropriate styling, and be accessible to users of all abilities.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads