如何用rails命令编写我的SQL查询

时间:2017-05-03 06:08:56

标签: ruby-on-rails ruby postgresql sqlcommand

我的sql命令是这样的。我试图与两个表关系。我需要使用rails helpers查询ruby命令。

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

我的数据库方案:

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或与分支有关系。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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