计算 Rails 中的记录总数 join table

Count total number of records in Rails join table

我有两个模型,用户和部门,还有一个联接 table users_departments 以启用它们之间的 has_and_belongs_to_many 关联。我正在使用 PostgreSQL 作为数据库。

# users table columns
id
name

# departments table columns
id
name

# users_departments table columns
user_id
department_id

Rails 中计算 users_departments table 中记录总数的最佳方法是什么?最好不要创建新模型 class.

请注意,我不想计算特定用户或部门的记录数 (user.departments.count / departments.users.count),而是 table 的总记录数,考虑到所有用户和部门。

最好的方法是只创建一个名为 UsersDepartment 的模型,然后对其进行简单易用的查询。

count = UsersDepartment.count

您可以直接查询 table,但是可以使用 exec_query which gives you an ActiveRecord::Result 对象。

result = ActiveRecord::Base.connection.exec_query('select count(*) as count from users_departments')
count = result[0]['count']