如何使用Rails 3 activerecord编写此sql查询?

时间:2012-07-27 16:38:13

标签: ruby-on-rails activerecord

我正在尝试使用Rails 3 activerecord约定编写此查询。

SELECT s.name, s.id FROM tripoli_schools_development.campus_programs cp 
  JOIN tripoli_schools_development.career_categories cc ON cp.career_category_id = cc.id 
  JOIN tripoli_schools_development.campuses c ON c.id = cp.campus_id 
  JOIN tripoli_schools_development.schools s ON s.id = c.school_id 
 WHERE cp.enabled = true and c.enabled = true and s.enabled = true and cc.id = 2 
 group by s.id order by s.name

以下是我的模特:

class CampusProgram < TripoliSchool
  belongs_to :career_category
  belongs_to :campus
end

class CareerCategory < TripoliSchool
  has_many :career_programs
  has_many :campus_programs
end

class Campus < TripoliSchool
  self.table_name = 'campuses'
  belongs_to :school
  has_many :campus_programs
end

class School < ActiveRecord::Base
  has_many :campuses, :class_name => "Campus"
  has_many :campus_programs, :through => :campuses
end

和所有重要的

class TripoliSchool < ActiveRecord::Base
  self.abstract_class = true
  establish_connection "tripoli_schools_#{Rails.env}"
end

2 个答案:

答案 0 :(得分:0)

试试这个:

CompusProgram.select("shcools.name, shcools.id").joins([:career_categories, {:campuses => :schools}]).where("campus_programs.enabled = true and campuses.enabled = true and schools.enabled = true and career_categories.id = 2 ")

我不确定但你有这个主意。您可以在此处查看文档:{​​{3}}。

答案 1 :(得分:0)

这要归功于Dougui和anthonyalberto

CampusProgram.select("schools.name, schools.id").joins(:career_category).joins(:campus => :school).where("campus_programs.enabled = true and campuses.enabled = true and schools.enabled = true and career_categories.id = 2").group("schools.id").order("schools.name")

这也有效

CampusProgram.select("schools.name, schools.id").joins([:career_category, {:campus => :school}]).where("campus_programs.enabled = true and campuses.enabled = true and schools.enabled = true and career_categories.id = 2").group("schools.id").order("schools.name")