From fcff4e80d1484bcb5ae7c4bb50640c52c9e98709 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Wed, 11 Sep 2013 14:50:26 -0400 Subject: [PATCH] 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. --- app/models/user.rb | 8 ++++++++ app/models/user_stat.rb | 5 +++++ db/migrate/20130911182437_create_user_stats.rb | 15 +++++++++++++++ spec/models/user_stat_spec.rb | 12 ++++++++++++ 4 files changed, 40 insertions(+) create mode 100644 app/models/user_stat.rb create mode 100644 db/migrate/20130911182437_create_user_stats.rb create mode 100644 spec/models/user_stat_spec.rb diff --git a/app/models/user.rb b/app/models/user.rb index 59f51326964..ec65794733c 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -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 @@ -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: @@ -538,6 +540,12 @@ class User < ActiveRecord::Base 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 diff --git a/app/models/user_stat.rb b/app/models/user_stat.rb new file mode 100644 index 00000000000..6d9dc27042c --- /dev/null +++ b/app/models/user_stat.rb @@ -0,0 +1,5 @@ +class UserStat < ActiveRecord::Base + + belongs_to :user + +end diff --git a/db/migrate/20130911182437_create_user_stats.rb b/db/migrate/20130911182437_create_user_stats.rb new file mode 100644 index 00000000000..66f5370743c --- /dev/null +++ b/db/migrate/20130911182437_create_user_stats.rb @@ -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 diff --git a/spec/models/user_stat_spec.rb b/spec/models/user_stat_spec.rb new file mode 100644 index 00000000000..8d30dd8d7b6 --- /dev/null +++ b/spec/models/user_stat_spec.rb @@ -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 \ No newline at end of file