0

所以我有两张桌子:

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

我正在尝试获取申请者 pr 专业化的总数。在 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 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
);
4

0 回答 0