0

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.

2
  • what result are you expecting from query at the end? Commented May 3, 2017 at 6:12
  • I want to merge branch's courses and show_all_branches field selected in courses table but i want to do this rails/active_record helpers. Commented May 3, 2017 at 6:16

1 Answer 1

1

You can do this:

    sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)
Sign up to request clarification or add additional context in comments.

4 Comments

Or if you are trying to find or count by sql command try this api.rubyonrails.org/classes/ActiveRecord/Querying.html
Thanks. Actually i mean do that by rails helpers not completely sql commands.
Tell me what are you writing and what results you are getting and also what is required
Im writing this CourseContent.show_all_branches.merge(-> { joins(:branches) }) but its return show_all_branches selected and has relation to branches. I actually need show_all_branches selected or has relation to branches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.