Ruby: Rails controller actions
This documentation is part of the Learning Ruby guide. You can view the complete guide here: A comprehensive Ruby and Rails guide.
👋 Welcome to the Stackhero documentation!
Stackhero provides a ready-to-use Ruby cloud solution offering a range of advantages, including:
- Deploy your application within seconds using a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Take advantage of automatic backups, one-click updates, and clear, transparent, and predictable pricing.
- Enjoy optimal performance and enhanced security thanks to a private, dedicated infrastructure.
Save time and make your life easier: it only takes 5 minutes to try Stackhero's Ruby cloud hosting solution!
Controllers serve as the intermediary between models and views by receiving incoming requests and rendering the appropriate responses. The following examples illustrate common controller actions for listing, showing, creating, updating, and deleting resources:
-
Index action (list all objects):
def index @objects = ModelName.all end -
Show action (display a single object):
def show @object = ModelName.find(params[:id]) end -
New action (display form for a new object):
def new @object = ModelName.new end -
Create action (save a new object):
def create @object = ModelName.new(params.require(:model_name).permit(:field1, :field2)) if @object.save redirect_to @object else render :new end end -
Edit action (display form for editing an existing object):
def edit @object = ModelName.find(params[:id]) end -
Update action (apply changes to an existing object):
def update @object = ModelName.find(params[:id]) if @object.update(params.require(:model_name).permit(:field1, :field2)) redirect_to @object else render :edit end end -
Destroy action (delete an object):
def destroy @object = ModelName.find(params[:id]) @object.destroy redirect_to model_name_path end