I have a Proposal model and a Signature model.
Proposal has many signatures and Signature belongs to proposal
My relationships work fine when I select a single Proposal, but when I do a Proposal.search and return multiple proposals, I can’t access signatures.
I want to sort my proposals by signatures count, so I tried this:
Proposal.find(:all, :limit => 3, :include => [:signatures])
Now when I debug(@proposals) I do see the corresponding signatures. How do I access them and write an :order => signatures.count ?
I’m not very familiar with includes / joins …so let me know if I’m going about this the wrong way. Thanks.
:includeis used when you will need to access the signatures later. If all you need is the count of associated signatures for sorting, then you do not need:include.I don’t especially like the following, but it seems to work:
First, the
:joinsparameter means that for each Proposal record you will get another row in the output for each associated Signature. The:groupparameter combines those rows into one, but only after the:orderparameter sorts based on the number of rows for each proposal.id (and hence number of signatures).I suspect there is a better way, but this seems to work.