DonMB
DonMB

Reputation: 2728

Count attributes in child model through has_many association

I have two models:

user.rb attributes: name, gender

and

participation.rb attributes: user_id + some other

A user has_many :participations A participation belongs_to :user

I now simply want to find out how many males do I have for a participation collection:

@participations = Participation.all
@males = @participations.joins(:user).where(gender: 'male').count

I understood it this way that I have to join the user model through participations like in the above snippet but that does not work.

Another way would be to simply write:

@males = @participations.users.where(gender: 'male').count

I think I misunderstood something essential here. How can I solve my problem "the rails way"?

Upvotes: 0

Views: 86

Answers (3)

Alexander Shlenchack
Alexander Shlenchack

Reputation: 3869

Also you can use eager loading with :includes:

@males = @participations.includes(:user).where(users: {gender: 'male'})

Upvotes: 2

David Aldridge
David Aldridge

Reputation: 52396

I would define a males scope on the user, and then define a new association "males" or "male_users" on participants into which you merge that scope, to allow you to:

@participations.male_users.count

Upvotes: 0

Marek Lipka
Marek Lipka

Reputation: 51191

You should specify table name in your query, like this:

@males = @participations.joins(:user).where(users: {gender: 'male'})

Upvotes: 1

Related Questions