这是我的数据库计划:
branches
-----------------------------------
id
name:string
active:boolean
..
course_contents
-----------------------------------
id
title:string
show_all_branches:boolean
active:boolean
..
branches_course_contents
-----------------------------
branch_id
course_content_id
我的模特档案:
class Branch < ApplicationRecord
has_and_belongs_to_many :course_contents
scope :active, -> { where(active: true) }
end
class CourseContent < ApplicationRecord
has_and_belongs_to_many :branches
scope :active, -> { where(active: true) }
scope :show_all_branches, -> { where(show_all_branches: true) }
end
我试图CourseContent.show_all_branches.merge(-> { joins(:branches) })
这个命令。它返回选择的show_all_branches,并与branches表有关系。但我需要选择show_all_branches或与branches表有关系。
答案 0 :(得分:0)
感谢您的帮助。我解决了这个问题,并为其他人编写了我的解决方案。我说实际上需要使用在course_contents表中选择的show_all_branches来分支course_contents。我尝试使用此CourseContent.show_all_branches.merge(-> { joins(:branches) })
的合并方法或其他许多方法与其他条件。因为我曾经加入/包括所有条件的方法。它永远不会为我返回真实的结果。我终于尝试了left_joins方法,这解决了我的问题。
我的命令在这里:
@course.course_contents.active.left_joins(:branches).where("course_contents.show_all_branches = ? OR branches_course_contents.branch_id = ?", true, @branch.id)
其sql结果
SELECT "course_contents".* FROM "course_contents" LEFT OUTER JOIN "branches_course_contents" ON "branches_course_contents"."course_content_id" = "course_contents"."id" LEFT OUTER JOIN "branches" ON "branches"."id" = "branches_course_contents"."branch_id" WHERE "course_contents"."course_id" = 3 AND "course_contents"."active" = 't' AND (course_contents.show_all_branches = 't' OR branches_course_contents.branch_id = 1)
及其解释:
CACHE (0.0ms) SELECT "course_contents".* FROM "course_contents" LEFT OUTER JOIN "branches_course_contents" ON "branches_course_contents"."course_content_id" = "course_contents"."id" LEFT OUTER JOIN "branches" ON "branches"."id" = "branches_course_contents"."branch_id" WHERE "course_contents"."course_id" = $1 AND "course_contents"."active" = $2 AND (course_contents.show_all_branches = 't' OR branches_course_contents.branch_id = 1) [["course_id", 3], ["active", true]]
Branch Load (1424.1ms) SELECT "branches".* FROM "branches" WHERE "branches"."active" = $1 AND "branches"."slug" = $2 LIMIT $3 [["active", true], ["slug", "izmir"], ["LIMIT", 1]]