Adding a JOIN between two tables

て烟熏妆下的殇ゞ 提交于 2019-12-12 03:53:37

问题


Here is the classes I have:

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')

Now I want to list the top 10 expensive classes

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.


回答1:


There's a typo in your scope: joins:(:programs) should be joins(:programs)

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]})


来源:https://stackoverflow.com/questions/15256258/adding-a-join-between-two-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!