How do I add a count property to an item in a collection in Rails?
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. (Ea开发者_运维问答ch 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
With just the award you have no way of knowing which user you're referencing (which you've learned in having to use award.times_won(user)
.
Does the following line up with your use cases?
class User < ActiveRecord::Base
def award_counts
@count_hash ||= self.user_awards.count(:all,:group=>:award_id)
end
def award_count(award_id)
award_counts[award_id] || 0
end
end
精彩评论