我的sql命令是這樣的。我試圖與兩張桌子關係。我需要用rails helpers寫查詢來ruby命令。如何用rails命令寫我的sql查詢
select *,
(select branch_id
from branches_course_contents
where course_content_id=course_contents.id and branch_id=2) as Sube
from course_contents
where
(select branch_id
from branches_course_contents
where course_content_id=course_contents.id and branch_id=2)=2
or show_all_branches=true)
and content_type=0
我的DB計劃:
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,並與分公司的關係。我其實需要選擇show_all_branches或與分支有關係。
,您在查詢末期待什麼結果呢? –
我想合併分支的課程和show_all_branches在課程表中選擇的字段,但我想做這個rails/active_record助手。 –