How to show error message on rails views?
Solution 1
The key is that you are using a model form, a form that displays the attributes for an instance of an ActiveRecord model. The create action of the controller will take care of some validation (and you can add more validation).
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.
new
View displays error messages from the model that failed to save
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? %>
<ul>
<% @simulation.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% 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 %>
Solution 2
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 %>
Comments
-
Amit Pal almost 2 years
I am newbie in
rails
and want to apply validation onform
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 messageThanks in advance
-
rii over 6 yearsYou have an extra if here:
<% if f.object.errors.each do |message| %>
Tried to edit but it's less than 6 characters so I it would not let me do it.