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 that delivers numerous advantages, including:

  • Deploy your application in just a few seconds with a simple git push.
  • Use your own domain name and take advantage of automatic configuration of HTTPS certificates for enhanced security.
  • Benefit from automatic backups, one-click updates, and clear, transparent, and predictable pricing.
  • Enjoy optimal performance and enhanced security thanks to a private, dedicated VM.

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:

  1. Index action (list all objects):

    def index
      @objects = ModelName.all
    end
    
  2. Show action (display a single object):

    def show
      @object = ModelName.find(params[:id])
    end
    
  3. New action (display form for a new object):

    def new
      @object = ModelName.new
    end
    
  4. 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
    
  5. Edit action (display form for editing an existing object):

    def edit
      @object = ModelName.find(params[:id])
    end
    
  6. 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
    
  7. Destroy action (delete an object):

    def destroy
      @object = ModelName.find(params[:id])
      @object.destroy
      redirect_to model_name_path
    end