I get user, volunteer, and event must exist, when I try to post a student as json data in postman to my rails backend student table

Viewed 27

I don't understand why I am getting a 422 on http request, I feel I put all parameters I needed into my request, cant someone tell me what is wrong with this cond.

this is my controllers trusted parameters

    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def user_params
      params.require(:user).permit(:name, :email, :password)
    end
end


I have a user, event, volunteer with id 2

[
    {
        "id": 2,
        "name": "otis guess",
        "address": "195 Garfield ave",
        "contact": 860303,
        "user_id": 2,
        "event_id": 2,
        "volunteer_id": 2,
        "created_at": "2022-09-09T11:25:28.252Z",
        "updated_at": "2022-09-09T11:25:28.252Z"
    }
]

here is my controller

class StudentsController < ApplicationController
  before_action :set_student, only: %i[ show update destroy ]

  # GET /students
  def index
    @students = Student.all

    render json: @students
  end

  # GET /students/1
  def show
    render json: @student
  end

  # POST /students
  def create
    @student = Student.new(student_params)

    if @student.save
      render json: @student, status: :created, location: @student
    else
      render json: @student.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /students/1
  def update
    if @student.update(student_params)
      render json: @student
    else
      render json: @student.errors, status: :unprocessable_entity
    end
  end

  # DELETE /students/1
  def destroy
    @student.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_student
      @student = Student.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def student_params
      params.require(:student).permit(:name, :address, :contact, :User_id, :Event_id, :Volunteer_id)
    end
end

response is 422

{
    "user": [
        "must exist"
    ],
    "event": [
        "must exist"
    ],
    "volunteer": [
        "must exist"
    ]
}

What is wrong with this request, as I feel all of it is fine.

{
    "student": {
        "name": "Dom",
        "address": "112 connecticut ave",
        "contact": "86030",
        "user_id": 2,
        "event_id": 2,
        "volunteer_id": 2 
    }
}

model

class User < ApplicationRecord
    has_many :students, dependent: :destroy 
    has_many :events, dependent: :destroy 
    has_many :volunteers, dependent: :destroy 
    
    # validates :username, presence: true, uniqueness: true
    # validates :email, presence: true, uniqueness: true
    # validates :email, format: { with: URI::MailTo::EMAIL_REGEXP }
    # validates :password, length: { minimum: 6 }

    
end

0 Answers
Related