How to show error message in rails views?
I'm new to rails
and want to apply validation in form
.
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 a field row
in the model class and return an error if it is not in the range. I can check the range of the above code but cannot return the error
Thank you in advance
source to share
Change your controller as shown 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
Then in your new view, if there is an error, you can print everything as shown 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 %>
source to share
You just need to add this code to your view ( myviewsnew.html.erb
) file :
<%= error_messages_for :simulation %>
Check the full syntax error_messages_for
at http://apidock.com/rails/ActionView/Helpers/ActiveRecordHelper/error_messages_for
source to share