Commit 0fa4fa83

mo k <mo@mokhan.ca>
2012-08-08 04:17:59
build a new avatar if one does not exist.
1 parent 5d040a5
Changed files (3)
app
controllers
uploaders
views
registrations
app/controllers/avatars_controller.rb
@@ -1,15 +1,23 @@
 class AvatarsController < ApplicationController
   before_filter :authenticate_user!
+  before_filter :find_or_build_avatar
 
   def create
-    @avatar = current_user.avatar.build(params[:avatar])
+    @avatar.avatar = params[:avatar]
+    if @avatar.save
+      redirect_to(profiles_mine_path, :notice => 'Your new avatar has been uploaded.') 
+    else
+      flash[:error] = "could not upload photo"
+    end
+  end
 
-    respond_to do |format|
-      if @avatar.save
-        format.html { redirect_to(current_user, :notice => 'Your new avatar has been uploaded.') }
-      else
-        flash[:error] = "could not upload photo"
-      end
+  protected 
+  def find_or_build_avatar
+    if current_user.avatar == nil
+      @avatar = current_user.avatar = Avatar.new
+      current_user.save
+    else
+      @avatar = current_user.avatar
     end
   end
 end
app/uploaders/avatar_uploader.rb
@@ -4,6 +4,7 @@ class AvatarUploader < CarrierWave::Uploader::Base
 
   # Include RMagick or MiniMagick support:
   include CarrierWave::RMagick
+  include CarrierWave::MimeTypes
   # include CarrierWave::MiniMagick
 
   # Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
@@ -31,6 +32,10 @@ class AvatarUploader < CarrierWave::Uploader::Base
   process :resize_to_fit => [1160, 870]
   process :convert => 'png'
 
+  version :thumb do
+    process :resize_to_fill => [260, 260]
+  end
+
   # Provide a default URL as a default if there hasn't been a file uploaded:
   # def default_url
   #   # For Rails 3.1+ asset pipeline compatibility:
app/views/registrations/edit.html.erb
@@ -92,5 +92,11 @@
         <%= f.password_field :password_confirmation %>
         <%= f.submit "Change My Password", :class=>"btn btn-primary" %>
       <% end %>
+        <%= form_tag(avatars_path(current_user), :method => "post", :multipart => true) do |f| %>
+          <%= fields_for Avatar.new do |f| %>
+            <%= f.file_field :avatar, :rel => avatars_path(current_user) %>
+            <input type="submit" class="btn primary" value="Add avatar" />
+          <% end %>
+        <% end %>
     </div>
   </div>