- Create a new rails project named ValidationErrors.
- Generate a model named Student with these fields:
Field | Datatype |
fname | string |
major | string |
year | integer |
gpa | float |
- Generate a non-scaffold-based controller with name Students
and views add_new and display_all.
- Source code for the controller
School2/app/controllers/students_controller.rb.
- Source code for the view
Student2/app/views/students/add_new.html.erb
- Source code for the view
Student2/app/views/students/display_all.html.erb.
- Add a POST route for the display_all view in the
routes file:
post 'students/display_all'
- 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 }
- View the questions view in a browser at this URL:
http://localhost:3000/students/add_new
- 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.
- 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
- In the add_new view, after the h1 header, add this ERB code:
<pre style="font-family: arial;">
<%= flash[:notice] %>
</pre>
- In the display_all view, after the h1 header, add this line of ERB code:
<%= @msg %>
- Test the application again, adding new students with and without validation errors.