Added plantings_count (i.e. counter_cache) to Member

Also removed the superfluous .plantings_count method on Crop, which was
causing some confusion.

A thing we learned today: we should use .size to find the size of
ActiveRecord collections, not .count, because .count doesn't use the
cache (while .size does).
This commit is contained in:
Skud
2013-08-26 12:41:10 +10:00
parent 73b7897c28
commit 42e3b5e04e
5 changed files with 18 additions and 2 deletions

View File

@@ -6,7 +6,7 @@ class Planting < ActiveRecord::Base
:quantity, :sunniness, :planted_from, :owner_id
belongs_to :garden
belongs_to :owner, :class_name => 'Member'
belongs_to :owner, :class_name => 'Member', :counter_cache => true
belongs_to :crop, :counter_cache => true
has_and_belongs_to_many :photos

View File

@@ -0,0 +1,5 @@
class AddPlantingsCountToMember < ActiveRecord::Migration
def change
add_column :members, :plantings_count, :integer
end
end

View File

@@ -11,7 +11,7 @@
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20130826012139) do
ActiveRecord::Schema.define(:version => 20130826023159) do
create_table "account_types", :force => true do |t|
t.string "name", :null => false
@@ -116,6 +116,7 @@ ActiveRecord::Schema.define(:version => 20130826012139) do
t.float "longitude"
t.boolean "send_notification_email", :default => true
t.text "bio"
t.integer "plantings_count"
end
add_index "members", ["confirmation_token"], :name => "index_users_on_confirmation_token", :unique => true

View File

@@ -156,6 +156,13 @@ namespace :growstuff do
end
end
desc "August 2013: initialize member planting counter"
task :initialize_member_planting_count => :environment do
Member.find_each do |m|
Member.reset_counters m.id, :plantings
end
end
end
end

View File

@@ -11,3 +11,6 @@ rake growstuff:oneoff:set_default_crop_creator
echo "2013-08-26 - set planting owner"
rake growstuff:oneoff:set_planting_owner
echo "2013-08-26 - initialize member planting count"
rake growstuff:oneoff:initialize_member_planting_count