【发布时间】:2011-01-10 04:53:01
【问题描述】:
我有一个涉及用户和奖项的数据模型,并由 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),但我想知道当它在 user.award 的上下文中时是否有办法包装 Award,以便我知道它被赢得了多少次.我无法动态添加属性,因为我只是得到一个 NoMethodError
【问题讨论】:
标签: ruby oop activerecord collections object