korywka
korywka

Reputation: 7653

Items count for has_many/belongs_to

I have 2 models: Manufacturer and Car

Car belongs to Manufacturer, Manufacturer has many Cars

When person is searching for car, i want to show them only those manufacturer in list, that have Cars in DB (hide manufacturers without cars).

I added field 'count' to Manufacturer, but dont know how better to keep it up to date when Car is added/destroyed?

Upvotes: 2

Views: 292

Answers (1)

Maurício Linhares
Maurício Linhares

Reputation: 40313

Since you already have the count field, just add it's configuration to your car model:

class Car < ActiveRecord::Base
  belongs_to :manufacturer, :counter_cache => :counter
end

Now, whenever you add a new car, the counter field in Manufacturer will be incremented. You will need to properly fill this field now as you already have a database.

Also, if you had not defined the counter field already, Rails default would be using a field named as cars_counter (instead of just counter) and then at the counter_cache definition you would have it only as counter_cache => true instead of naming the column as counter.

Upvotes: 5

Related Questions