【问题标题】:Count total number of records in Rails join table计算 Rails 连接表中的记录总数
【发布时间】:2020-11-22 00:21:35
【问题描述】:

我有两个模型,用户和部门,以及一个连接表 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 表中记录总数的最佳方法是什么?最好不要创建新的模型类。

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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

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

    count = UsersDepartment.count
    

    您可以使用exec_query 直接查询表,这会为您提供ActiveRecord::Result 对象。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      相关资源
      最近更新 更多