[英]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 这在SQL中非常简单
eg 例如
SELECT *
FROM students
JOIN teachers
ON students.id = teachers.student_id
How can I do the same in rails? 如何在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 需要注意的是最终目标很简单,就是能够在控制器中创建一个实例变量,这样我可以在视图访问教师和学生数据
Student.includes(:teacher)
will return ActiveRecord::CollectionProxy
which means if take particular object in this collection, it will be Student
class object. Student.includes(:teacher)
将返回ActiveRecord::CollectionProxy
,这意味着如果接受此集合中的特定对象,它将是Student
类对象。
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. 与从2个表中触发并返回数据的sql查询不同,它在rails中无法正常工作,您只能从“
students
列中获取数据,该数据将与teachers
表中的关联记录相关联,因为它表示“ Student
模型。
You can access further teachers
data like, 您可以访问其他
teachers
数据,例如,
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 在上面,当您在对象上调用
teacher
关联时,不会在数据库中触发任何新查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.