Hey All,
I’m currently working on a Guitar Reviews website and I think i’ve been
coding for way to long and forgot the basics…I’m having trouble doing a
simple SQL method.
I have 2 Tables, 1 for Guitar Manufacturers (gmanufacturers) and 1 for
Guitar Models (gmodels), every model has a manufacturer and every
manufacturer has many models (gmodel belongs_to :gmanufacturer &
gmanufacturer has_many :gmodels). What i’m trying to do is; when I list
all of the gmanufacturers, I want to show how many models each
manufacturer has, ex:
Manufacturer 1
[ 2 Models ]
Manufacturer 2
[ 15 Models ]
etc…
So, I assume I would have to loop the result of a Gmanufacturer.find
:all into a Gmodel.count statement, but havent been able to come up with
anything.
Forgive me if this is a bit too confusing…just reply and i’ll explain
better.
Thanks!
Eric,
You should be able to do a loop over all manufacturers and put each
into a manufacturer variable. Then:
[ <%= gmanufacturer.gmodels.count %> Models ]
should give you the result you are looking for. If you add an :include
=> [:gmodels] to your find then you will get the results with only one
call to the database. Here is a full example:
@gmanufacturers = GManufacturers.find(:all, :include =>[:gmodels])
Carl F. wrote:
Eric,
You should be able to do a loop over all manufacturers and put each
into a manufacturer variable. Then:
[ <%= gmanufacturer.gmodels.count %> Models ]
should give you the result you are looking for. If you add an :include
=> [:gmodels] to your find then you will get the results with only one
call to the database. Here is a full example:
@gmanufacturers = GManufacturers.find(:all, :include =>[:gmodels])
Thanks Carl. That worked perfectly. Except, I came up with another
annoying feature I might need…
Would it be possible to define a condition for the count? like, where
approved = ‘true’?
Thanks,
Try something like,
gmanufacturer.gmodels.find(:all, :conditions => “approved = ‘true’”)
If you are looking for approved manufacturers:
@gmanufacturers = GManufacturers.find(:all, :include => [:gmodels],
:conditions => [“approved = ‘true’”])
If you are looking for approved models:
@gmanufacturers = GManufacturers.find(:all, :include => [:gmodels],
:conditions => [“gmodels.approved = ‘true’”])
Check out the docs for find. They are pretty good.