开发者

How do I add a count property to an item in a collection in Rails?

开发者 https://www.devze.com 2022-12-18 03:07 出处:网络
I have a data model involving Users and Awards, and joined by a user_awards table. class User < ActiveRecord::Base

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
0

精彩评论

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

关注公众号