Ruby On Rails表单:如何将文本及下拉字段设为必填项?
Hey there! Let's break down and fix your two issues step by step:
To ensure users can't submit the form without selecting an option from the dropdown, you'll want to add validation both on the frontend and backend (frontend for immediate user feedback, backend to enforce the rule even if frontend validation is bypassed).
Frontend Validation (HTML/Rails Form Helper)
If you're writing plain HTML, add the required attribute directly to your <select> tag:
<select name="student[your_dropdown_field]" required> <!-- Your dropdown options here --> </select>
If you're using Rails form helpers, pass the required: true option in the HTML attributes hash:
# In your form view <%= form_with(model: @student) do |f| %> <!-- Other form fields --> <%= f.select :your_dropdown_field, YourOptionModel.all.pluck(:name, :id), {}, { required: true } %> <%= f.submit "Save" %> <% end %>
Backend Validation (Model Level)
Add a presence validation to your Student model to guarantee the field is never saved as empty:
# app/models/student.rb class Student < ApplicationRecord # Your existing validations/associations validates :your_dropdown_field, presence: true end
That error means the params[:id] value being passed to your destroy action is empty or missing. Let's troubleshoot this:
Step 1: Check Your Delete Link/Button
Make sure your delete link is correctly passing the student's ID. In Rails, use the singular path helper (student_path(@student)) and specify the method: :delete:
<!-- In your student index/show view --> <%= link_to "Delete Student", student_path(@student), method: :delete, data: { confirm: "Are you sure you want to delete this student?" } %>
If you accidentally use the plural students_path instead of student_path(@student), it won't pass the id parameter, leading to the error.
Step 2: Verify Your Routes
Run rails routes in your terminal and confirm there's a RESTful DELETE route for /students/:id pointing to students#destroy. It should look like this:
DELETE /students/:id(.:format) students#destroy
Step 3: Add a Safety Check in the Controller
To avoid hard crashes even if the ID is missing, use find_by instead of find and handle the missing student case gracefully:
# app/controllers/students_controller.rb def destroy @student = Student.find_by(id: params[:id]) if @student @student.destroy redirect_to students_path, notice: "Student deleted successfully." else redirect_to students_path, alert: "Student not found." end end
内容的提问来源于stack exchange,提问作者absolado

