Introduction
Action methods handle requests in a Rails controller. They decide what to do when a user visits a page or sends data.
Action methods handle requests in a Rails controller. They decide what to do when a user visits a page or sends data.
def action_name # code to handle request end
def index
@items = Item.all
enddef show
@item = Item.find(params[:id])
enddef create @item = Item.new(item_params) if @item.save redirect_to @item else render :new end end
This controller has two action methods. index sets a list of fruits. show gets an item name from the URL parameter.
class ItemsController < ApplicationController def index @items = ['apple', 'banana', 'cherry'] end def show @item = params[:id] end end
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.
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.
action method in a Rails controller?show in a Rails controller?def method_name; end.def index @users = User.all end
@users contain after this action runs?User.all in RailsUser.all fetches all records from the users table as an ActiveRecord collection (like an array).@usersdef create
@user = User.new(params[:user])
if @user.save
redirect_to @user
else
render :new
end
endparams[:user] directly is unsafe and will cause an error in modern Rails.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?Post.find(params[:id]).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.post_path(@post) which is also correct.Pass the test and this pattern moves unknown