Rails后端POST请求返回422错误排查:user、event、volunteer必须存在问题
Hey there, I see exactly what's causing that frustrating 422 error! Let's break it down:
Your error message says user, event, and volunteer must exist, even though you're sending the correct user_id, event_id, and volunteer_id in your request. The problem lies in how your controller is filtering parameters.
Look at your student_params method in StudentsController:
def student_params params.require(:student).permit(:name, :address, :contact, :User_id, :Event_id, :Volunteer_id) end
You're using camel-cased keys (:User_id, :Event_id, :Volunteer_id) here, but your request sends snake-cased ones (user_id, event_id, volunteer_id). Rails treats these as completely different parameters, so your controller is not actually allowing the IDs you're sending to pass through to the Student model. Without those IDs, Rails triggers the default presence validation for your belongs_to associations (Rails 5+ enables this by default), hence the error.
The Fix
Update your student_params to use the correct snake-cased parameter names:
def student_params params.require(:student).permit(:name, :address, :contact, :user_id, :event_id, :volunteer_id) end
Quick Additional Checks
Just to be thorough:
- Make sure your
Studentmodel has the correctbelongs_toassociations defined (this is almost certainly the case since you're getting those specific validation errors):class Student < ApplicationRecord belongs_to :user belongs_to :event belongs_to :volunteer end - Double-check that your Postman request has the
Content-Typeheader set toapplication/json— this ensures Rails parses your JSON body correctly.
After making that parameter name fix, your create request should work as expected!
内容的提问来源于stack exchange,提问作者Otis Guess

