In my rails project, I have a query which finds the 10 most recent contests and orders by their associated poll dates:
@contests = Contest.find(
:all,
:limit => "10",
:include => :polls,
:order => "polls.start_date DESC" )
Currently this shows each contest and then iterates through associated polls sorting the master list by poll start date.
Some of these contests have the same :geo
, :office
and :cd
attributes. I would like to combine those in the view, so rather than listing each contest and iterating through each associated poll (as I'm doing right now), I'd like to iterate through each unique combinati开发者_JS百科on of :geo
, :office
and :cd
and then for each "group," iterate through all associated polls regardless of associated contest
and sort by polls.start_date.
I'd like to do this without having to create more cruft in the db.
Unless I've misunderstood, I think you might be looking for this:
@contests.group_by { |c| [c.geo, c.office, c.cd] }
It gives you a Hash, keyed on [c.geo, c.office, c.cd]
, each entry of which contains an Array of the contests that share the combination.
精彩评论