我需要将数据附加到变量中。
@celebrity = Celebrity.includes(:category).where('category_id = ?', params[:id])
test =[]
@celebrity.each do |celeb|
@vote = Vote.where('celebrity_id = ?', celeb).count
test << {vote_count:@vote}
end
当我调试“测试”时,
abort test.inspect
我得到的结果是
[{:vote_count=>2}, {:vote_count=>1}, {:vote_count=>0}]
但是,我的问题是我怎样才能把vote_count附加到@名人,有谁能帮我一下吗?
发布于 2015-09-02 09:01:31
@celebrity.each do |celeb|
celeb["vote_count"] = celeb.votes.count
end
他说得对。使用counter_caches
发布于 2015-09-02 09:00:21
你不应该这样做,这在性能上很糟糕。
如果您正确地设置了一个counter_cache
(见参考文献),您就可以按照预期在模型实例中立即获得数据。
https://stackoverflow.com/questions/32348591
复制相似问题