0

Im using Rails 5 and I wanna doing has_and_belongs_to_many relation with other query. Its instead of merge two queries but its not same. Actually I wanna do this clean way.

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

How can i do it clean?

@branch.course_contents.active + CourseContent.show_all_branches

I want to write this sql output with rails. That sql command works fine for me.

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
Ilya Lavrov
  • 2,810
  • 3
  • 20
  • 37

1 Answers1

0

Try this:

@branch.course_contents.active.merge(CourseContent.show_all_branches)
archana
  • 1,282
  • 8
  • 11