user1010101
user1010101

Reputation: 1658

Proper way to handle exceptions in Ruby on Rails

I have a simple form where I collect user inputs for two fields. I have pasted the code below to display the form.

<%= form_tag("/welcome/index", method: "post") do %>
  <%= label_tag :longitude %><br>
  <%= text_field_tag :longitude %>
  <br>
  <br>
  <%= label_tag :latitude %><br>
  <%= text_field_tag :latitude %>
  <p>
    <%= submit_tag("Submit") %>
  </p>
<% end %>

In the controller, I capture the user's input and display relevant information.

class WelcomeController < ApplicationController
  # displays the form, so change the name of the form you have now to new.html.erb
  def new
  end

  # the form will pass to this action to perform logic on longitude and latitude
  def create
    longitude = params[:longitude]
    latitude = params[:latitude]
    @stops = Stop.where("longitude = ? AND latitude = ?", longitude, latitude)
    render :index
  end

  # if it renders from the create action, @stops will be available to use here
  def index
  end
end

There can be some cases where the user does not fill anything in the form and hits submit. I was wondering how do I properly handle such a case in Ruby on Rails. I am fairly new to Ruby on Rails. For instance in Java I would throw exception saying

No input provided

So I would like to display some message on such cases. I would appreciate if someone can show me how this can be done.

Upvotes: 0

Views: 52

Answers (2)

msergeant
msergeant

Reputation: 4801

You can check if either field is nil in your create method:

def create
    longitude = params[:longitude]
    latitude = params[:latitude]
    if(longitude.blank? || latitude.blank?)
      # render something here to display the error
    else
      @stops = Stop.where("longitude = ? AND latitude = ?", longitude, latitude)
      render :index
    end
  end

Upvotes: 0

errata
errata

Reputation: 26792

In rails you will want to use Active Record Validations on your model. http://guides.rubyonrails.org/active_record_validations.html

validates :name, presence: true

There are various way to do this, and I usually submit forms with angularjs and return errors as JSON but since it looks like you are using standard html form actions, here is an example of a "user" creation form,

def create
  user = User.create(user_params)
  if @user.save
    flash[:notice] = "User has been created"
    redirect_to user_path(@user)
  else
    flash[:error] = "Somethig is wrong"
    render :new
  end
end



<% form_for @user do |f| %>
  <%= f.error_messages %>
  <%= f.label :name, "Enter your name:" %><br>
  <%= f.text_field :name %><br>
  <%= submit_tag "Send" $>
<% end %>

Upvotes: 2

Related Questions