轨道上的一对多关系ruby

时间:2012-06-07 06:19:11

标签: ruby-on-rails

所以我有两张桌子:

class Applicant < ActiveRecord::Base
  set_table_name "applicant"
  belongs_to :specialization, :foreign_key => "id"
end

class Specialization < ActiveRecord::Base
  set_table_name "specialization"
  has_many :applicant, :foreign_key => "id"
end

我正在努力获得申请人专业化的总数。在SQL中会是这样的:

SELECT a.Name, COALESCE(b.total,0) AS "Total Applicants"
FROM specialization AS a
    LEFT JOIN ( SELECT specialization.Name, COUNT(*) as total
                FROM applicant
        JOIN specialization ON applicant.specialization = specialization.id
        GROUP BY specialization.name) AS b
ON a.name = b.name
ORDER BY a.name;

如何使用RoR执行此操作?到目前为止,我尝试过的是:

<% Specialization.includes(:applicant).all.each do |s| %>
    <tr>
        <td><%= s.name%></td>
        <td><%= s.applicant.count()%></td>
    </tr>
<% end %>

这似乎不起作用,因为我在一些专业领域只计算1名申请人,我从查看我的数据库知道在某些专业领域有4名申请人。

编辑: 它是一个pg SQL数据库,SQL文件中的create table命令是这样的:

CREATE TABLE Specialization (
    Id  SERIAL PRIMARY KEY,
    Name    TEXT
);

CREATE TABLE Applicant (
    Id              SERIAL PRIMARY KEY,
    FirstName       TEXT,
    MiddleInitial   TEXT,
    LastName        TEXT,
    Specialization  INTEGER REFERENCES Specialization (id) NOT NULL
);

0 个答案:

没有答案