【问题标题】:How do I add a count property to an item in a collection in Rails?如何在 Rails 的集合中添加计数属性?
【发布时间】: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


    【解决方案1】:

    仅凭奖项,您无法知道您引用的是哪个用户(您在必须使用 award.times_won(user) 时学到了这一点。

    以下是否符合您的用例?

    
    class User &lt 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
    

    【讨论】:

    • 这可行,但它只返回奖项的 ID。我想知道是否有办法将实际奖励作为哈希键返回?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    相关资源
    最近更新 更多