My sql command like this. Im trying to relation with two tables. I need the write that query to ruby command with rails helpers.
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
My DB schemes:
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
And model files:
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
Im trying like this CourseContent.show_all_branches.merge(-> { joins(:branches) }) but it returns show_all_branches selected and has relation with branches. I actually need show_all_branches selected or has relation with branches.