Ruby: Rails controller actions
This documentation is part of the Learning Ruby guide. View the full guide here: A comprehensive Ruby and Rails guide.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Ruby cloud solution that provides a host of benefits, including:
- Deploy your application in seconds with a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
- Get optimal performance and robust security thanks to a private and dedicated VM.
Save time and simplify your life: 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