Read more

Rails: How to use custom flash types in controllers

Emanuel
January 18, 2021Software engineer at makandra GmbH

Rails supports alert and notice as default flash types. This allows you to use these keys as options in e.g. redirect_to and as a helper in views e.g. <%= notice %> (instead of flash[:notice]).

class SomeController < ApplicationRecord
  def create
    @user = User.create!
    
    redirect_to user_path(@user), notice: "#{@user} created!" 
  end
end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

In case you are using Bootstrap as CSS framework you might also want to support flashes like success. This can be done with the add_flash_types method.

class ApplicationController < ActionController::Base
  add_flash_types :success
end
class SomeController < ApplicationRecord
  def create
    @user = User.create!
    
    # Before adding success as flash type
    # flash[:success] = "#{@user} created!" 
    # redirect_to user_path(@user)

    # After adding success as flash type
    redirect_to user_path(@user), success: "#{@user} created!" 
  end
end
Posted by Emanuel to makandra dev (2021-01-18 12:41)