我正在寻找一种方法来显示有多少images
有category
,但通过has_many
关联获得。我一直在阅读上counter_cache
一点点,但至今尚无欢乐上实现有效的方法来计算关联的对象 - Rails 4
class Category < ActiveRecord::Base
has_many :image_categories
has_many :images, through: :image_categories
end
class ImageCategory < ActiveRecord::Base
# Holds image_id and category_id to allow multiple categories to be saved per image, as opposed to storing an array of objects in one DB column
belongs_to :image
belongs_to :category
end
class Image < ActiveRecord::Base
# Categories
has_many :image_categories, dependent: :destroy
has_many :categories, through: :image_categories
end
控制器
@categories = Category.all
查看
<% @categories.each do |c| %>
<li>
<%= link_to '#', data: { :filter => '.' + c.name.delete(' ') } do %>
<%= c.name %> (<%= #count here %>)
<% end %>
</li>
<% end %>
如果有人可以帮助那些将不胜感激
谢谢
谢谢,关于如何实现的任何想法?如上所述,尚未成功实施 – Richlewis
@Richlewis请参阅更新后的答案 – Alfie
请注意,您可能需要使用'reset_counters'将count列初始化为其正确值'http://apidock.com/rails/ ActiveRecord/CounterCache/reset_counters' –