To Examples

Directions for ValidationErrors Example

  1. Create a new rails project named ValidationErrors.
  2. Generate a model named Student with these fields:
    Field Datatype
    fname string
    major string
    year integer
    gpa float
  3. Generate a non-scaffold-based controller with name Students and views add_new and display_all.
  4. Source code for the controller School2/app/controllers/students_controller.rb.
  5. Source code for the view Student2/app/views/students/add_new.html.erb
  6. Source code for the view Student2/app/views/students/display_all.html.erb.
  7. Add a POST route for the display_all view in the routes file:
    post 'students/display_all'
    
  8. Add these validations to the app/models/student.rb file:
    validates :fname, presence: true
    validates :year, numericality: 
      { only_integer: true }
    validates :gpa, numericality: 
      { greater_than_or_equal_to: 0.0, 
        less_than_or_equal_to: 4.0 } 
    
  9. View the questions view in a browser at this URL:
    http://localhost:3000/students/add_new
    
  10. Try adding new rows to the students database with and without validation errors. Notice that the rows are added only if no violations are violated.
  11. In the controller, replace the statements
     @student.save
    @a = Student.all
    
    with these statements:
    if @student.save
      @msg = 'New student was successfully created'
      @a = Student.all
    else
      if @student.errors.any?
        cnt = @student.errors.count
        error_messages = cnt.to_s + " " + "error".pluralize(cnt) + 
          " prohibited this student from being saved.\n"
        @student.errors.full_messages.each do |msg|
          error_messages += "--" + msg + ".\n"
        end
      end
      redirect_to students_add_new_path, notice: error_messages
    end 
    
  12. In the add_new view, after the h1 header, add this ERB code:
  13. In the display_all view, after the h1 header, add this line of ERB code:
    <%= @msg %>
    
  14. Test the application again, adding new students with and without validation errors.