0

我正在尝试使用 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
4

2 回答 2

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 ")

我不确定,但你有这个想法。您可以在此处查看文档:http: //api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

于 2012-07-27T17:03:48.270 回答
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")
于 2012-07-27T17:25:23.923 回答