cereallarceny
cereallarceny

Reputation: 4983

How can I see how many users have a particular association in Rails?

I'm trying to figure out how I can use the Rails console to get the number of users that have two particular associations. Here's my conditions:

A User can have many DropboxUser accounts linked and many DriveUser accounts linked to their account via a foreign key. In my model declaration, both DropboxUser and DriveUser belongs_to :user. In conjunction with the previous statement, a User has_many :dropbox_users and has_many :drive_users. I know I have all of my models linked, so now I want to know how I can find out how many User accounts have both a DropboxUser account and a DriveUser account associated with them.

Here's some of the code I've tried (unsuccessfully):

User.count(:conditions => "dropbox_users.uid='user.id' AND drive_users.uid='user_id'")

Perhaps I was headed in the right direction with my last query, perhaps not. It told me no such column: dropbox_users.uid.

Upvotes: 0

Views: 50

Answers (1)

Sean Hill
Sean Hill

Reputation: 15056

You have to join dropbox_users to be able to query on it.

User.joins(:dropbox_users).joins(:drive_users).count

Also, since joins uses an INNER JOIN, it will only return records that have both Dropbox and Drive accounts.

Upvotes: 1

Related Questions