1

I have a model called Partners and a model called Profiles.

A partner has many profiles and a profile has one partner.

I need a way to count in the partners controller to return how many profiles they have.

In the profiles table the column is called : partner_id which is the same as the id column in the partners table.

I have seen the .count() function but cannot work out what I need to return the correct number

Cheers

3 Answers3

10

I think the best way will be to use counter_cache column:

class Partner < ActiveRecord::Base
  has_many :profiles, :dependent => :destroy
end

class Profile < ActiveRecord::Base
  belongs_to :partner, :counter_cache => true
end

you should add profiles_count column to partners table. It's not a good way to call @partner.profiles.count because it will perform additional query to the database. You should use @partner.profiles.size instead. It will get size of collection if it has been already retrieved from the database and perform query in another case. For more details please visit following links:

Community
  • 1
  • 1
tiktak
  • 1,801
  • 2
  • 26
  • 46
1
@partner = Partner.find params[:id] 
@partner.profiles.count

should do the trick

Reuben Mallaby
  • 5,740
  • 4
  • 47
  • 45
1

If you have

has_many :profiles 

on Partner class and @partner instantiated in your controller, then you can do:

@partner.profiles.count