在两个表之间添加 JOIN [英] Adding a JOIN between two tables
问题描述
这是我的课程:
Model Organization
has_many Students
Model Student
has_many Classes
belongs_to Organization
Model Class
a field named : price
belongs_to Student
scope :top_expensive_classes, joins(:students).order('price DESC')
现在我要列出最昂贵的 10 个课程
至少我遇到的第一个问题是,在 params
中,我有 organization_id
可以根据它进行过滤,但是我像这样编写控制器,但它不起作用,因为它认为它应该在 Class
模型中找到 organization_id 但它在 Student
模型中.
At least the first problem I have is that in the params
I have the organization_id
to filter based on that But I write my controller like this which does NOT work because it thinks it should find organization_id in the Class
model but it is in the Student
model.
@results = Class.top_expensive_classes.where(organization_id: params[:id]).limit(RESULT_SET_COUNT)
所以我想知道是否有办法解决这个问题?我想我应该在某个地方引入一个新的连接?但想不通.
So I was wondering if there is a way to fix this? I think I should introduce a new join somewhere? but couldn't figure it out.
推荐答案
你的范围中有一个错字:joins:(:programs)
应该是 joins(:programs)
There's a typo in your scope: joins:(:programs)
should be joins(:programs)
要根据 Student 中的组织 ID 进行提取,您可以这样做:
To fetch based on the organization id in Student you may be able to do this:
@results = Class.top_expensive_classes
.joins(student: :organization)
.where(organization: {id: params[:id]})
这篇关于在两个表之间添加 JOIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!