views:

41

answers:

1

I have a data model involving Users and Awards, and joined by a user_awards table.

class User < ActiveRecord::Base
  :has_many :user_awards
  :has_many :awards, :through => :user_awards  # awards the user has won
end

class Award < ActiveRecord::Base
  :has_many :user_awards
  :has_many :users, :through => :user_awards
end

I'd like there to be a 'times_won' property such that I can determine how many times a user has won a particular award. (Each granting of the award is a row in the user_awards join table)

i.e. Id like to to this:

>> user = User.find(777)
>> award = user.awards[0]
>> award.times_won  # and get the number of times  
                    # this user has won this particular award

So far I've added a method Award.times_won_by( user ), but I'm wondering if there's a way to wrap the Award when it's in this context of user.award so that I know how many times it's been won. I can't add the property dynamically, as I just get a NoMethodError

+1  A: 
klochner
This works, but it just returns the ID of the award. I'm wondering if there is a way to return the actual award as the hash key?
Scelerat
you can use :group=>:award
klochner