【发布时间】:2021-01-27 14:02:47
【问题描述】:
假设,数据库中有三张表:
课程(:id, :name)
course_details(:course_id, :effective_date, :status),
course_codes(:course_detail_id, :code)
课程有很多 course_details
course_detail 有很多课程代码
课程可以有多个 course_details 记录,这些记录是有效日期的(意味着系统中只会使用一个 course_detail 记录)。
问题说明:我想通过给定代码的课程代码过滤课程。并且课程应该只被与有效日期 course_detail 链接的 course_codes 过滤,并且应该跳过过去的有效日期记录。
course = Course.find(params[:id])
course_detail = CourseDetail.find_by(effective_date: CourseDetail.max(effective_date), course_id: course.id)
如果我使用此代码,这将过滤课程,而不考虑有效日期的课程详细信息:
Course.left_joins(course_details: :course_codes).where(course_details: { course_codes: { code: params[:code] } })
课程:
| Id | Name |
|---|---|
| 1 | English |
| 2 | Maths |
课程详情:
| id | course_id | effective_date |
|---|---|---|
| 1 | 1 | 2020-10-01 |
| 2 | 1 | 2021-01-01 |
| 3 | 2 | 2020-09-01 |
课程代码:
| id | course_detail_id | code. |
|---|---|---|
| 1 | 1 | eng-01 |
| 2 | 2 | eng-505 |
| 3 | 3 | math-01 |
当我通过 code = eng-01 时,它应该返回空数组,而不是 id 1。
有人可以帮帮我吗?
【问题讨论】:
-
您能否提供数据样本和预期结果?
-
@max 示例数据已添加。
标签: ruby-on-rails ruby postgresql subquery ruby-on-rails-6.1