我是rails
的新手,想在form
的領域申請驗證。如何在rails視圖上顯示錯誤消息?
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
我要檢查row
場的整數範圍模型類和如果它不在範圍內,則返回錯誤消息。我可以從上面的代碼檢查範圍,但不能提前返回錯誤信息
感謝
http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of ...完成。 – zee
@NullSoulException我正在做同樣的事情。我想以 –