如何在Rails中为集合中的项添加count属性?

时间:2010-01-27 23:28:48

标签: ruby oop activerecord collections object

我有一个涉及用户和奖项的数据模型,并由user_awards表加入。

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

我希望有一个'times_won'属性,以便我可以确定用户赢得特定奖励的次数。 (每次授予奖励都是user_awards连接表中的一行)

即。我想这样:

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

到目前为止,我已经添加了一个方法Award.times_won_by(用户),但是我想知道是否有一种方法可以在这个user.award的上下文中包含奖励,这样我就知道赢了多少次。我无法动态添加属性,因为我得到NoM​​ethodError

1 个答案:

答案 0 :(得分:1)

只有奖励,您无法知道您引用的是哪个用户(您必须使用award.times_won(user)时学到的。

以下是否与您的用例对齐?


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