Bird
Raised Fist0
Ruby on Railsframework~10 mins

Action methods in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Action methods
HTTP Request Received
↓
Router Matches URL
↓
Controller Selected
↓
Action Method Called
↓
Action Executes Code
↓
Render View or Redirect
↓
HTTP Response Sent
When a web request comes in, Rails finds the right controller and calls the action method, which runs code and sends back a response.
Execution Sample
Ruby on Rails
class BooksController < ApplicationController
  def show
    @book = Book.find(params[:id])
  end
end
This action method finds a book by its ID and prepares it for the view to display.
Execution Table
StepActionCode ExecutedState ChangeOutput/Next Step
1Receive HTTP GET /books/3Router matches to BooksController#showController set to BooksControllerCall show action method
2Call show method@book = Book.find(params[:id])@book set to Book with id=3Prepare data for view
3Render viewRender show.html.erb with @bookView ready with @book dataSend HTTP response with HTML
4Response sentHTTP 200 OK with book detailsRequest completeEnd
💡 Action method finishes after rendering view or redirecting, response sent to client
Variable Tracker
VariableStartAfter Step 2Final
@booknilBook(id=3, title='Example')Book(id=3, title='Example')
Key Moments - 2 Insights
Why does the action method need to set instance variables like @book?
Instance variables like @book are used to pass data from the action method to the view template, as shown in step 2 and 3 of the execution_table.
What happens if the action method does not render or redirect?
Rails will try to render the default view matching the action name automatically after the action method finishes, as seen in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of @book after step 2?
ABook with id=3
Bnil
Cparams[:id]
DEmpty object
💡 Hint
Check the 'State Change' column in step 2 of the execution_table
At which step does Rails send the HTTP response back to the client?
AStep 1
BStep 4
CStep 2
DStep 3
💡 Hint
Look at the 'Output/Next Step' column for when the response is sent
If the action method did not set @book, what would happen in the view rendering step?
AView renders with empty @book
BRails skips rendering the view
CView raises an error for missing @book
DRails redirects automatically
💡 Hint
Instance variables must be set in the action method to be used in the view (see variable_tracker)
Concept Snapshot
Action methods are controller functions called by Rails when a matching URL is requested.
They run code to prepare data, usually setting instance variables.
After running, Rails renders a view or redirects.
Instance variables connect controller data to views.
If no render or redirect, Rails renders default view automatically.
Full Transcript
In Rails, when a web request comes in, the router finds the right controller and action method. The action method runs code, often setting instance variables like @book to pass data to the view. After the action runs, Rails renders the matching view template or redirects. The HTTP response is then sent back to the client. This flow ensures the right data is shown on the page. If the action method does not explicitly render or redirect, Rails automatically renders the default view for that action. Instance variables are key to sharing data between the controller and the view.

Practice

(1/5)
1. What is the primary role of an action method in a Rails controller?
easy
A. To respond to user requests by processing data and rendering views or redirects
B. To define database schema and migrations
C. To style the HTML pages with CSS
D. To manage server configuration settings

Solution

  1. Step 1: Understand the purpose of action methods

    Action methods in Rails controllers handle user requests by processing data and deciding what to show next.
  2. Step 2: Differentiate from other roles

    Database schema, styling, and server settings are handled elsewhere, not in action methods.
  3. Final Answer:

    To respond to user requests by processing data and rendering views or redirects -> Option A
  4. Quick Check:

    Action methods handle requests = A [OK]
Hint: Action methods handle requests and responses in controllers [OK]
Common Mistakes:
  • Confusing action methods with database migrations
  • Thinking action methods style pages
  • Assuming action methods configure servers
2. Which of the following is the correct syntax to define an action method named show in a Rails controller?
easy
A. function show() {}
B. def show; end
C. show() => {}
D. def show() {}

Solution

  1. Step 1: Recall Ruby method syntax in Rails controllers

    Rails controller actions are Ruby methods defined with def method_name; end.
  2. Step 2: Identify correct syntax

    def show; end uses correct Ruby syntax without parentheses, which is common in Rails.
  3. Final Answer:

    def show; end -> Option B
  4. Quick Check:

    Ruby method syntax = A [OK]
Hint: Rails actions use Ruby method syntax: def name; end [OK]
Common Mistakes:
  • Using JavaScript function syntax
  • Adding parentheses with braces in Ruby
  • Mixing arrow functions with Ruby
3. Given this Rails controller action:
def index
  @users = User.all
end

What will @users contain after this action runs?
medium
A. A hash of user attributes
B. A single User record
C. An array of all User records from the database
D. An empty array

Solution

  1. Step 1: Understand User.all in Rails

    User.all fetches all records from the users table as an ActiveRecord collection (like an array).
  2. Step 2: Determine the content of @users

    It will contain all user records, not just one or empty or a hash.
  3. Final Answer:

    An array of all User records from the database -> Option C
  4. Quick Check:

    User.all returns all records = D [OK]
Hint: User.all fetches all records as a collection [OK]
Common Mistakes:
  • Thinking User.all returns a single record
  • Assuming it returns a hash
  • Confusing with empty array if no users exist
4. Identify the error in this Rails controller action:
def create
  @user = User.new(params[:user])
  if @user.save
    redirect_to @user
  else
    render :new
  end
end
medium
A. Missing an end keyword
B. Using render instead of redirect_to in else
C. Redirecting to @user instead of a URL string
D. Using params[:user] directly without strong parameters

Solution

  1. Step 1: Check parameter handling in create action

    Rails requires strong parameters to whitelist allowed attributes for security.
  2. Step 2: Identify misuse of params[:user]

    Using params[:user] directly is unsafe and will cause an error in modern Rails.
  3. Final Answer:

    Using params[:user] directly without strong parameters -> Option D
  4. Quick Check:

    Strong parameters needed = B [OK]
Hint: Always use strong parameters for mass assignment [OK]
Common Mistakes:
  • Ignoring strong parameters security
  • Thinking redirect_to needs a URL string only
  • Missing end keyword (not true here)
5. You want to add a custom action method publish to your PostsController that changes a post's status to 'published' and then redirects to the post's page. Which code snippet correctly implements this?
hard
A. def publish @post = Post.find(params[:id]) @post.status = 'published' @post.save redirect_to post_path(@post) end
B. def publish @post = Post.find(params[:id]) @post.status = 'published' redirect_to post_path(@post) end
C. def publish @post = Post.find(params[:id]) @post.status = 'published' redirect_to @post end
D. def publish @post = Post.find(params[:id]) @post.save(status: 'published') redirect_to @post end

Solution

  1. Step 1: Find the post by ID

    All options correctly find the post using Post.find(params[:id]).
  2. Step 2: Update the post's status and save changes

    def publish @post = Post.find(params[:id]) @post.status = 'published' redirect_to @post end changes status but does not save. def publish @post = Post.find(params[:id]) @post.status = 'published' redirect_to post_path(@post) end changes status but does not save. def publish @post = Post.find(params[:id]) @post.status = 'published' @post.save redirect_to post_path(@post) end changes status, calls save, then redirects. def publish @post = Post.find(params[:id]) @post.save(status: 'published') redirect_to @post end incorrectly uses save(status: 'published') which is invalid.
  3. Step 3: Redirect to the post's show page

    Options A, C, and D redirect correctly. def publish @post = Post.find(params[:id]) @post.status = 'published' redirect_to post_path(@post) end uses post_path(@post) which is also correct.
  4. Final Answer:

    def publish @post = Post.find(params[:id]) @post.status = 'published' @post.save redirect_to post_path(@post) end -> Option A
  5. Quick Check:

    Change attribute + save + redirect = C [OK]
Hint: Change attribute, save record, then redirect [OK]
Common Mistakes:
  • Forgetting to save after changing attribute
  • Using invalid save syntax with parameters
  • Not redirecting after update
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard