Commit 1f5009e6

mo khan <mo@mokhan.ca>
2013-06-17 04:19:20
add favorites counter cache
1 parent 98a7284
app/models/favorite.rb
@@ -1,5 +1,5 @@
 class Favorite < ActiveRecord::Base
   belongs_to :user
-  belongs_to :creation
+  belongs_to :creation, :counter_cache => true
   attr_accessible :user_id, :creation_id
 end
app/views/shared/_creation_image_gallery.html.erb
@@ -6,8 +6,8 @@
       <h3><a href="<%= url_for creation %>"><%= short_name(creation, 15) %></a></h3>
       <h4><small><a href="<%= url_for profile_path(creation.user) %>"><%= shrink(creation.user.name, 20) %></a></small></h4>
       <p>
-      <a href="<%= url_for creation_favorites_path(:creation_id => creation.id) %>"><span><%= creation.favorites.count %></span><i class="icon-heart"></i></a>
-      <a href="<%= url_for creation %>#comments"><span class="badge badge-success" title="<%= pluralize( creation.comment_threads.count, "comments") %>"><%= creation.comment_threads.count %></span></a>
+      <a href="<%= url_for creation_favorites_path(:creation_id => creation.id) %>"><span><%= creation.favorites.size %></span><i class="icon-heart"></i></a>
+      <a href="<%= url_for creation %>#comments"><span class="badge badge-success" title="<%= pluralize( creation.comment_threads.size, "comments") %>"><%= creation.comment_threads.size %></span></a>
       </p>
     </div>
     </li>
db/migrate/20130617041448_add_favorites_count_to_creations.rb
@@ -0,0 +1,13 @@
+class AddFavoritesCountToCreations < ActiveRecord::Migration
+  def up
+    add_column :creations, :favorites_count, :integer, :default => 0
+    Creation.reset_column_information
+    Creation.find_each do |creation|
+      Creation.reset_counters creation.id, :favorites
+    end
+  end
+
+  def down
+    remove_column :creations, :favorites_count
+  end
+end
db/schema.rb
@@ -11,7 +11,7 @@
 #
 # It's strongly recommended to check this file into your version control system.
 
-ActiveRecord::Schema.define(:version => 20130617040733) do
+ActiveRecord::Schema.define(:version => 20130617041448) do
 
   create_table "active_admin_comments", :force => true do |t|
     t.integer  "resource_id",   :null => false
@@ -88,9 +88,10 @@ ActiveRecord::Schema.define(:version => 20130617040733) do
     t.datetime "updated_at"
     t.integer  "user_id"
     t.string   "image"
-    t.boolean  "is_restricted", :default => false, :null => false
+    t.boolean  "is_restricted",   :default => false, :null => false
     t.string   "watermark"
-    t.integer  "photos_count",  :default => 0
+    t.integer  "photos_count",    :default => 0
+    t.integer  "favorites_count", :default => 0
   end
 
   add_index "creations", ["created_at"], :name => "index_creations_on_created_at"