stevec
stevec

Reputation: 52268

How to retrieve all of one table and all joined records in another with the other table's columns in ActiveRecord

I would like to retrieve all of one table and all joined records in another.

I would like to have all columns from both tables

This is extremely simple in SQL

e.g.

SELECT * 
FROM students
JOIN teachers
ON students.id = teachers.student_id

How can I do the same in rails?

I've tried variations on

Student.includes(:teacher)

and

Student.joins(:teacher).includes(:teacher)

The join is working, but I cannot access columns from Teacher table

Note that the end goal is simply to be able to create an instance variable in the controller so that I can access both student and teacher data in the view

Upvotes: 0

Views: 1610

Answers (1)

ray
ray

Reputation: 5552

Student.includes(:teacher) will return ActiveRecord::CollectionProxy which means if take particular object in this collection, it will be Student class object.

Unlike sql query fired and returning data from 2 tables, it does not work same in rails, you get data only from students column which will relate associated record in teachers table because it represent Student model.

You can access further teachers data like,

  students = Student.includes(:teacher)
  students.last.teacher.name

In above no new query will get fired in database when you call teacher association on object

Upvotes: 1

Related Questions