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 online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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)