Skip to content

Instantly share code, notes, and snippets.

@tpendragon
Forked from anonymous/gist:5856301
Last active December 18, 2015 22:39
Show Gist options
  • Save tpendragon/5856321 to your computer and use it in GitHub Desktop.
Save tpendragon/5856321 to your computer and use it in GitHub Desktop.
class UpdateCache < ActiveRecord::Migration
def up
User.all.each do |user|
object = user
association = :pets
counter_name = :pets_count
User.connection.update("UPDATE #{User.quoted_table_name} SET #{User.connection.quote_column_name(counter_name)} = #{object.pets.count} WHERE #{User.connection.quote_column_name(User.primary_key)} = #{User.quote_value(object.id)}", "#{User.name} UPDATE")
end
end
def down
end
end
servers: [""]
[] executing command
** [out :: ] == UpdateCache: migrating ====================================================
** [out :: ]
** [out :: ] rake aborted!
** [out :: ]
** [out :: ] An error has occurred, this and all later migrations canceled:
** [out :: ]
** [out :: ]
** [out :: ] uninitialized constant User::Pet
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/inheritance.rb:111:in `compute_type'
** [out :: ]
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/reflection.rb:172:in `klass'
** [out :: ]
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:117:in `
klass'
** [out :: ]
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:123:in `
target_scope'
** [out :: ]
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:87:in `s
coped'
** [out :: ]
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.
rb:210:in `count'
** [out :: ]
** [out :: ] /var/www/Test/shared/bundle/ruby/1.9.1/gems/activerecord-3.2.13/lib/active_record/associations/collection_proxy.rb:46:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable,
:confirmable
validates :email, :presence => true, :uniqueness => true
validates :username, :presence => true, :uniqueness => true
# Pets
has_many :pets, :foreign_key => :owner_id
# @return [Pet] Active pet for this user.
def active_pet
self.pets.length > 0 ? self.pets[0] : nil
end
end
class Pet < ActiveRecord::Base
belongs_to :owner, :class_name => "User", :counter_cache => true
validates :owner, :presence => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment