Nikita
Nikita

Reputation: 155

How do I count within nested resourced and display the results?

I am building a job board in rails based on PostgreSQL. I want to count and display the amount of job offers per employer on the index of the employer page. What is the code for this kind of count?

I created a nested resource, and associated my employer and offer model, by:

class Employer < ActiveRecord::Base
  has_many :offers, dependent: :delete_all
end

Upvotes: 0

Views: 48

Answers (1)

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

You should use counter_cache i.e. adding an extra column(offer_count) in employer table & update the counter while making entry in offer table. For more details , check counter_cache in http://guides.rubyonrails.org/association_basics.html

Your migration should like

 def change
    add_column :employers, :offers_count, :integer, default: 0
    Employer.reset_column_information
    Employer.all.each do |p|
      Employer.update_counters p.id, :offers_count => p.offers.length
    end
  end

Upvotes: 1

Related Questions