Commit 0bbae07

Stephen Peasley <s@stephenpeasley.com>
2015-08-01 17:51:35
Create user profile upon user creation
1 parent 4a71616
app/models/profile.rb
@@ -1,3 +1,4 @@
 class Profile < ActiveRecord::Base
   belongs_to :user
+  enum social_tolerance: { low: 0, medium: 1, high: 2 }
 end
app/models/user.rb
@@ -8,6 +8,8 @@ class User < ActiveRecord::Base
   validates :username, presence: true, format: { with: USERNAME_REGEX }, uniqueness: true
   validates :email, presence: true, email: true, uniqueness: true
   validates_acceptance_of :terms_and_conditions
+  
+  after_create :create_profile
 
   def timezone
     TZInfo::Timezone.get('Canada/Mountain')
@@ -51,4 +53,13 @@ class User < ActiveRecord::Base
       user.authenticate(password)
     end
   end
+  
+  private
+  
+    def create_profile
+      self.profile = Profile.create!(user: self)
+      self.profile.social_tolerance = nil
+      self.save!
+    end
+  
 end
app/views/profiles/edit.html.erb
@@ -3,7 +3,7 @@
   <div class="small-12 columns text-center">
     <%= gravatar_for(@user, size: 128) %>
     <h1><%= @user.username %></h1>
-    <%= form_for @user do |f| %>
+    <%= form_for @user.profile do |f| %>
       <%= f.input :gender %>
       <%= f.input :social_tolerance %>
     <% end %>
db/migrate/20150616021904_create_profiles.rb
@@ -3,7 +3,7 @@ class CreateProfiles < ActiveRecord::Migration
     create_table :profiles do |t|
       t.uuid :user_id, null: false
       t.boolean :gender
-      t.integer :social_tolerance
+      t.integer :social_tolerance, default: 0
       t.timestamps null: false
     end
     add_index :profiles, :user_id
db/schema.rb
@@ -42,11 +42,11 @@ ActiveRecord::Schema.define(version: 20150616021904) do
   end
 
   create_table "profiles", force: :cascade do |t|
-    t.uuid     "user_id",          null: false
+    t.uuid     "user_id",                      null: false
     t.boolean  "gender"
-    t.integer  "social_tolerance"
-    t.datetime "created_at",       null: false
-    t.datetime "updated_at",       null: false
+    t.integer  "social_tolerance", default: 0
+    t.datetime "created_at",                   null: false
+    t.datetime "updated_at",                   null: false
   end
 
   add_index "profiles", ["user_id"], name: "index_profiles_on_user_id", using: :btree
spec/models/profile_spec.rb
@@ -2,11 +2,23 @@ require 'rails_helper'
 
 describe Profile do
   
+  let(:user) { create(:user) }
+  
+  describe "profile owner" do
+    it "has profile" do
+      expect(user.profile).to_not eql(nil)
+    end
+  end
+  
   describe "gender" do
-    it "defaults to no value" do
-      user = User.new(email: nil)
-      expect(user).to_not be_valid
-      expect(user.errors[:email]).to_not be_empty
+    it "defaults to unset" do
+      expect(user.profile.gender).to eql(nil)
+    end
+  end
+  
+  describe "social tolerance" do
+    it "defaults to unset" do
+      expect(user.profile.social_tolerance).to eql(nil)
     end
   end