现场验证Ruby on Rails

时间:2016-04-13 09:26:41

标签: ruby-on-rails ruby validation

我的表单字段验证有问题。我有两个文本字段需要验证才能继续下一页。验证运行正确,但验证消息显示为rails错误。

enter image description here

但我希望此错误如下enter image description here

任何人都知道为什么它的显示像rails错误。

型号:

class Assignment < ActiveRecord::Base
  include Workflow

  belongs_to :folder
  belongs_to :employee

  after_initialize :init_start_dateenter code here

  validates_presence_of :folder_id, :employee_id
end

控制器:

class AssignmentsController < ApplicationController
  def create
    @assignment = Assignment.new(assignment_params)

    respond_to do |format|
      if @assignment.save!
        format.html { redirect_to @assignment, notice: 'Assignment was successfully created.' }
        format.json { render :show, status: :created, location: @assignment }
        @assignment.folder.update({status: 'assigned'})
      else
        format.html { render :new }
        format.json { render json: @assignment.errors, status: :unprocessable_entity }
      end
    end
  end

end

我还有两个表单来验证字段。在该表格中,验证错误正确显示。

1 个答案:

答案 0 :(得分:2)

你需要从保存中删除!,因为这会在该行上抛出错误,如果省略!它只会返回一个布尔值(然后呈现错误或成功

所以

class AssignmentsController < ApplicationController
  def create
    @assignment = Assignment.new(assignment_params)

    respond_to do |format|
      if @assignment.save
        format.html { redirect_to @assignment, notice: 'Assignment was successfully created.' }
        format.json { render :show, status: :created, location: @assignment }
        @assignment.folder.update({status: 'assigned'})
      else
        format.html { render :new }
        format.json { render json: @assignment.errors, status: :unprocessable_entity }
      end
    end
  end

end