4856

How to show error message on rails views?

Question:

I am newbie in rails and want to apply validation on form fields.

myviewsnew.html.erb

<%= form_for :simulation, url: simulations_path do |f| %> <div class="form-group"> <%= f.label :Row %> <div class="row"> <div class="col-sm-2"> <%= f.text_field :row, class: 'form-control' %> </div> </div> </div> .....

Simulation.rb

class Simulation < ActiveRecord::Base belongs_to :user validates :row, :inclusion => { :in => 1..25, :message => 'The row must be between 1 and 25' } end

simulation_controller.rb

class SimulationsController < ApplicationController def index @simulations = Simulation.all end def new end def create @simulation = Simulation.new(simulation_params) @simulation.save redirect_to @simulation end private def simulation_params params.require(:simulation).permit(:row) end

I want to check the integer range of row field in model class and return the error message if it's not in the range. I can check the range from above code but not able to return the error message

Thanks in advance

Answer1:

The key is that you are using a model form, a form that displays the attributes for an instance of an ActiveRecord model. The <a href="https://guides.rubyonrails.org/active_record_basics.html#create" rel="nofollow">create action of the controller</a> will take care of some validation (and you can <a href="https://guides.rubyonrails.org/active_record_validations.html" rel="nofollow">add more validation</a>).

Controller re-renders new View when model fails to save

Change your controller like below:

def new @simulation = Simulation.new end def create @simulation = Simulation.new(simulation_params) if @simulation.save redirect_to action: 'index' else render 'new' end end

When the model instance fails to save (@simulation.save returns false), then the new view is re-rendered.

<h2>new View displays error messages from the model that failed to save</h2>

Then within your new view, if there exists an error, you can print them all like below.

<%= form_for @simulation, as: :simulation, url: simulations_path do |f| %> <% if @simulation.errors.any? %> <% @simulation.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> <% end %> <div class="form-group"> <%= f.label :Row %> <div class="row"> <div class="col-sm-2"> <%= f.text_field :row, class: 'form-control' %> </div> </div> </div> <% end %>

The important part here is that you're checking whether the model instance has any errors and then printing them out:

<% if @simulation.errors.any? %> <%= @simulation.errors.full_messages %> <% end %>

Answer2:

Do this -

<%= form_for :simulation, url: simulations_path do |f| %> <% if f.object.errors.any? %> <ul> <% if f.object.errors.each do |message| %> <li><%= message %></li> <% end %> </ul> <% end %> .......... <% end %>

Answer3:

You just need to add this code to the view file (myviewsnew.html.erb):

<%= error_messages_for :simulation %>

Check complete syntax of error_messages_for in <a href="http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_messages_for" rel="nofollow">http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_messages_for</a>

Recommend

  • How to use Middleware in Multiple Login system
  • /usr/bin/ld: cannot find shared library
  • Isabelle: Why do I get completely different results when running try versus sledgehammer
  • How can I use sklearn CountVectorizer with mutliple strings?
  • NHibernate.QueryException with dynamic-component
  • Text appearance, inside TextView and CardView
  • Convert a hashmap to a json string in spring-boot
  • Will HttpClient Async methods run in new threads
  • reason generics were introduced in java 5
  • Finding date & time in NSString using Regex
  • TeamCity: Scripting elements jsp:declaration, jsp:expression, jsp:scriptlet are disallowed here
  • Get Index of Item Text in MFC CListCtrl
  • Definitions of: AnsiString, WideString, String, char[], char*, BSTR,
  • Monkey patching ActiveResource::Errors
  • When using Shibboleth (v3) as SP , can I map the attribute value in attribute-map.xml?
  • Xcode. Image resources added to a test target are not copied into the tests bundle
  • Insertion Sort in C#
  • How to set a field containing unique key
  • WPF binding to property of all items in a collection
  • Progress bar shadow only on filled part
  • USB-Serial communication giving strange output
  • Show QMainwindow in the middle of the screen
  • Create a Windows driver to access network storage
  • Is the Windows App Store required for a UWP application?
  • Sending a PDF created dynamically as an attachment using PDFKit in a nodejs application
  • Cron and nightmarejs
  • Dynamic reference casting depending on actual object type
  • Silverlight MVVM, stop SelectionChanged triggering in response to ItemsSource reset
  • Webdriver 3.14 IE11: session lost when click link/button that opens a window/popup
  • Hyperlink to Outlook Attachment
  • What's the difference between using RDFS/OWL and XML?
  • Check if a file is a specific type in C
  • SELECT on JSONField with Django
  • Adding Dynamic Row and Data on Checkbox Click
  • Example of using Service Exists MSBuild task in Microsoft.Sdc.Tasks?
  • Circular Left Rotation Algorithm in C#
  • Checking for valid enum types from protobufs
  • Add checkbox dynamically using angular 2
  • how to run a different select statement based on condition in Hive SQL
  • read part of h5 dataset python