New user_stats table to keep track of queried information on a user.

This is information that is not usually needed when representing a user
and is in a separate table with a has one relationship to avoid querying
it all the time.
This commit is contained in:
Robin Ward 2013-09-11 14:50:26 -04:00
parent 95bfebefa4
commit fcff4e80d1
4 changed files with 40 additions and 0 deletions

View file

@ -35,6 +35,7 @@ class User < ActiveRecord::Base
has_one :github_user_info, dependent: :destroy has_one :github_user_info, dependent: :destroy
has_one :cas_user_info, dependent: :destroy has_one :cas_user_info, dependent: :destroy
has_one :oauth2_user_info, dependent: :destroy has_one :oauth2_user_info, dependent: :destroy
has_one :user_stat, dependent: :destroy
belongs_to :approved_by, class_name: 'User' belongs_to :approved_by, class_name: 'User'
has_many :group_users, dependent: :destroy has_many :group_users, dependent: :destroy
@ -60,6 +61,7 @@ class User < ActiveRecord::Base
after_save :update_tracked_topics after_save :update_tracked_topics
after_create :create_email_token after_create :create_email_token
after_create :create_user_stat
before_destroy do before_destroy do
# These tables don't have primary keys, so destroying them with activerecord is tricky: # These tables don't have primary keys, so destroying them with activerecord is tricky:
@ -538,6 +540,12 @@ class User < ActiveRecord::Base
end end
end end
def create_user_stat
stat = UserStat.new
stat.user_id = self.id
stat.save!
end
def create_email_token def create_email_token
email_tokens.create(email: email) email_tokens.create(email: email)
end end

5
app/models/user_stat.rb Normal file
View file

@ -0,0 +1,5 @@
class UserStat < ActiveRecord::Base
belongs_to :user
end

View file

@ -0,0 +1,15 @@
class CreateUserStats < ActiveRecord::Migration
def up
create_table :user_stats, :id => false do |t|
t.references :user, null: false
t.boolean :has_custom_avatar, default: false, null: false
end
execute "ALTER TABLE user_stats ADD PRIMARY KEY (user_id)"
execute "INSERT INTO user_stats (user_id) SELECT id FROM users"
end
def down
drop_table :user_stats
end
end

View file

@ -0,0 +1,12 @@
require 'spec_helper'
describe UserStat do
it { should belong_to :user }
it "is created automatically when a user is created" do
user = Fabricate(:evil_trout)
user.user_stat.should be_present
end
end