ArpithaGeorge
ArpithaGeorge

Reputation: 45

Field Validation Ruby on Rails

Having some trouble with my form field validation. I have two text field that requires validation before it persists to the next page. The validations are run correctly but the validation messages shows like rails error.

enter image description here

But I want this error like belowenter image description here

Any one Knows why its shows like rails error.

Model:

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

Controller:

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

I have two more forms to validate the fields. In that forms the validation errors are shows correctly.

Upvotes: 0

Views: 119

Answers (1)

JamesWatling
JamesWatling

Reputation: 1185

You need to remove the ! from the save, as this will throw an error on that line, if you omit the ! it will simply return a boolean (and then render the error or success.

so

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

Upvotes: 3

Related Questions