我使用Rails 5,我想与其他查询做has_and_belongs_to_many关系。它不是合并两个查询,而是不相同。其实我想干净利落。
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
我怎样才能干净?
@branch.course_contents.active + CourseContent.show_all_branches
我想用rails编写这个sql输出。那个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
答案 0 :(得分:0)
试试这个:
@branch.course_contents.active.merge(CourseContent.show_all_branches)