Rails 4 获取关联的记录和计数

Rails 4 Getting Record and Count of Associations

我有两个模型,

item.rb

class Item < ActiveRecord::Base
  belongs_to :user
  has_many :challenges
end

challenge.rb

class Challenge < ActiveRecord::Base
  belongs_to :user
  belongs_to :item
end

在我看来,我正在尝试进行计数

views/items/index.html.haml

- @items.each do |i|
  = i.challenge.count

挑战 有这些列:

item 有这些列


我遇到了这个错误

undefined method `challenge' for #

上线

= i.challenge.count

应该是challenges(复数名词)。

= i.challenges.count

顺便说一句,因为每次调用SQL计数是相当昂贵的,所以我建议使用counter_cache来提高查找归属对象数量的效率。

其实= i.challenges.count就可以了。

但是你应该使用counter_cache。

挑战模型

belongs_to :item, counter_cache: item

迁移

add_column :items, :challenges_count, :integer, default: 0

这些代码将有助于减少无用的数据库流量。