I have Project and Entry as models. Projects can have many entries, and entries belong to only a project. Entries have dates.
One reporting requirement is to show Projects that have Entries for a particular month. I have been successful in using scopes to achieve this, i.e. Project.with_entries.on(param_the_month).
The issue is that I now want to display the entries for that month only, grouped by projects.
If I do projects.each do |p|, then query for the entries (p.entries), the returned entries are for all months, not just the month I specified.
While this is an obvious result, is there a way in Rails to simply return the entries for that month using my original chained scope?
has-manyassociations also accept scopes, so you can doprojects.entries.your_scopeto filter them. The downside is that this would require another database query for every project, which might be slow depending on the size of your database.An alternative that does not require extra queries would be to fetch the entries already filtered, and then go upward to get the projects:
Now you have a hash whose keys are the projects, and the values are only the entries of that project that pass your conditions.