开发者

Filtering ActiveRecord queries by multiple unique attributes and combining results

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜