Home > Software engineering >  How to fetch data with relation in rails?
How to fetch data with relation in rails?

Time:09-23

I have students table that is related to schools table. The problem is, when I try to fetch all schools' data, it does not include the students that are associated in the api response.

But it more confuses me, student name was displayed in terminal when I try to loop and print. Although I have tried the below line but still won't work.

has_many :student, foreign_key: :school_id, primary_key: :id

Do you have idea why?


The students table has columns school_id that referenced to schools table.

schools_controller.rb

class SchoolsController < ApplicationController
  def index
    schools = School.includes(:student)

    schools.each do |school|
      puts school.student.collect(&:name) // student displayed in terminal
    end

    render json: { message: "sample", data: schools }, status: :ok
  end
end

school.rb

class School < ApplicationRecord
    has_many :student
end

student.rb

class Student < ApplicationRecord
end

12345_create_students.rb

class CreateStudents < ActiveRecord::Migration[7.0]
  def change
    create_table :students do |t|
      t.references :school, foreign_key: true
      t.string :name
      ...
    end
  end
end

CodePudding user response:

Model relations is actually fine. Your problem probably is in your controller.

Use preload instead of include, and in your return statement you should include the student.

learn the differences here

Your code should look like these:

schools = School.preload(:student)

render json: schools, include: :student

CodePudding user response:

Read https://guides.rubyonrails.org/association_basics.html for

and try below code

school.rb

class School < ApplicationRecord
    has_many :students
end

student.rb

class Student < ApplicationRecord
    belongs_to :school
end
  • Related