我正在尋找一種方法來顯示有多少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' –