Using Sinatra::Flash to Display Validation Error Messages

I created a to-do-list web application for my Sinatra project with Flatiron School and as an added feature, I used the Sinatra::Flash extension for setting and showing Rails-like flash messages. In particular, we want to display error messages generated by the Active Record validation process.

To set up, add the gem to your Gemfile and run bundle install.

gem ‘sinatra-flash’

In our app User model, we wrote a simple validation statement to ensure that only valid data is saved in our database. We want our new users to create valid and unique usernames as well as provide password to create an account.

class User < ActiveRecord::Base   has_many :lists   has_many :tasks, through: :lists   validates :username, presence: true, uniqueness: true   has_secure_passwordend

Next is to write the flash messages in our User controller file, to the post ‘/signup' action.

class UsersController < ApplicationController   get '/signup' do      erb :'users/signup.html'   end
post '/signup' do user = User.create(params[:user]) if user.valid? flash[:success] = "Account created!" session["user_id"] = user.id redirect '/tasks' else flash[:error] = user.errors.full_messages.to_sentence redirect '/signup' end endend

If when a user signs up and the data provided is valid, Sinatra flash will inform the user by displaying “Account is created!”. However, if invalid, we want our gem to display the error messages.

To display the messages, we added the below statement to the top of our view file users>signup.erb.

<% if flash[:error] %>   <p class="error"><%= flash[:error] %></div><%end%>

That’s it! We can implement this anywhere in our app and display validation errors to our app users. We can then add CSS styling to our messages however we’d like.

<% if flash[:error] %>   <p class="error"   style="background-color: #F8F8FF;   font-weight: bold;   padding: 20px;   max-width: 600px;">   <%= flash[:error] %>   </p><%end%>

A note on Error messages.

If signing up with blank username and password in our to-do-list app, it will flash “Username can’t be blank and Password can’t be blank”.

user.errors.full_messages.to_sentence # => Username can't be blank and Password can't be blank

If you would like to return a full message for only a given attribute, you can do full_message(attribute, message).

user.errors.full_message(:name, 'is invalid') # => "Name is invalid"

More on Active Model Errors here: https://api.rubyonrails.org/classes/ActiveModel/Errors.html

Thank you for reading!