2017-05-03 21 views
0

我的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或與分支有關係。

+0

,您在查詢末期待什麼結果呢? –

+0

我想合併分支的課程和show_all_branches在課程表中選擇的字段,但我想做這個rails/active_record助手。 –

回答

1

你可以這樣做:

sql = "Select * from ... your sql query here" 
records_array = ActiveRecord::Base.connection.execute(sql) 
+0

或者如果您正在嘗試通過sql命令查找或計數,請嘗試此操作:http://api.rubyonrails.org/classes/ActiveRecord/Querying.html –

+0

謝謝。其實我的意思是通過rails helpers來完成,而不是完全的sql命令。 –

+0

告訴我你在寫什麼,你得到了什麼結果,還有什麼是必需的 –