felipeecst
felipeecst

Reputation: 1415

Count total number of records in Rails join table

I have two models, users and departments, and a join table users_departments to enable a has_and_belongs_to_many association between them. I am using PostgreSQL as the database.

# users table columns
id
name

# departments table columns
id
name

# users_departments table columns
user_id
department_id

What is the best way in Rails for counting the total number of records in the users_departments table? Preferably without creating a new model class.

Please note that I do not want to count the records for a specific user or department (user.departments.count / departments.users.count), but the total number records for the table, considering all users and departments.

Upvotes: 0

Views: 1380

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14890

The best way is to just create a model called UsersDepartment and do a nice and easy query on that.

count = UsersDepartment.count

You can query the table directly however with exec_query which gives you an ActiveRecord::Result object to play with.

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

Upvotes: 2

Related Questions