Skip to content

Commit

Permalink
New user_stats table to keep track of queried information on a user.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
eviltrout committed Sep 11, 2013
1 parent 95bfebe commit fcff4e8
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class User < ActiveRecord::Base
has_one :github_user_info, dependent: :destroy
has_one :cas_user_info, dependent: :destroy
has_one :oauth2_user_info, dependent: :destroy
has_one :user_stat, dependent: :destroy
belongs_to :approved_by, class_name: 'User'

has_many :group_users, dependent: :destroy
Expand All @@ -60,6 +61,7 @@ class User < ActiveRecord::Base
after_save :update_tracked_topics

after_create :create_email_token
after_create :create_user_stat

before_destroy do
# These tables don't have primary keys, so destroying them with activerecord is tricky:
Expand Down Expand Up @@ -538,6 +540,12 @@ def update_tracked_topics
end
end

def create_user_stat
stat = UserStat.new
stat.user_id = self.id
stat.save!
end

def create_email_token
email_tokens.create(email: email)
end
Expand Down
5 changes: 5 additions & 0 deletions app/models/user_stat.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class UserStat < ActiveRecord::Base

belongs_to :user

end
15 changes: 15 additions & 0 deletions db/migrate/20130911182437_create_user_stats.rb
Original file line number Diff line number Diff line change
@@ -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
12 changes: 12 additions & 0 deletions spec/models/user_stat_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit fcff4e8

Please sign in to comment.