将数据附加到数组 rails 4
append data to an array rails 4
我需要将数据附加到变量
@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
当我调试 'test',
abort test.inspect
我正在得到
的结果
[{:vote_count=>2}, {:vote_count=>1}, {:vote_count=>0}]
但是,我的问题是如何将 vote_count 附加到 @celebrity ,谁能帮帮我
你不应该这样做,它在性能方面很糟糕。
如果您正确设置了 counter_cache
(see ref),您将立即在模型实例中获得预期的数据
@celebrity.each do |celeb|
celeb["vote_count"] = celeb.votes.count
end
+呼吸暂停是对的。使用 counter_caches
我需要将数据附加到变量
@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
当我调试 'test',
abort test.inspect
我正在得到
的结果[{:vote_count=>2}, {:vote_count=>1}, {:vote_count=>0}]
但是,我的问题是如何将 vote_count 附加到 @celebrity ,谁能帮帮我
你不应该这样做,它在性能方面很糟糕。
如果您正确设置了 counter_cache
(see ref),您将立即在模型实例中获得预期的数据
@celebrity.each do |celeb|
celeb["vote_count"] = celeb.votes.count
end
+呼吸暂停是对的。使用 counter_caches