0
0
Ruby on Railsframework~5 mins

Action methods in Ruby on Rails

Choose your learning style9 modes available
Introduction

Action methods handle requests in a Rails controller. They decide what to do when a user visits a page or sends data.

When you want to show a list of items on a webpage.
When you need to display a form for users to fill out.
When you want to save data sent by a user to the database.
When you want to update or delete existing data.
When you want to redirect users to another page after an action.
Syntax
Ruby on Rails
def action_name
  # code to handle request
end
Action methods are defined inside a controller class.
The method name usually matches the route or URL you want to handle.
Examples
This action fetches all items to show on the index page.
Ruby on Rails
def index
  @items = Item.all
end
This action finds one item by its ID to display details.
Ruby on Rails
def show
  @item = Item.find(params[:id])
end
This action creates a new item and redirects or re-renders the form based on success.
Ruby on Rails
def create
  @item = Item.new(item_params)
  if @item.save
    redirect_to @item
  else
    render :new
  end
end
Sample Program

This controller has two action methods. index sets a list of fruits. show gets an item name from the URL parameter.

Ruby on Rails
class ItemsController < ApplicationController
  def index
    @items = ['apple', 'banana', 'cherry']
  end

  def show
    @item = params[:id]
  end
end
OutputSuccess
Important Notes

Action methods must be public to be accessible by routes.

Use instance variables (like @item) to pass data to views.

Rails automatically renders a view matching the action name unless you redirect or render something else.

Summary

Action methods respond to user requests in Rails controllers.

They usually fetch or change data and then show a view or redirect.

Use clear method names matching the purpose, like index, show, create.