forked from carrierwaveuploader/carrierwave
-
Notifications
You must be signed in to change notification settings - Fork 0
How to: use carrierwave with devise
bartoszkopinski edited this page Aug 6, 2012
·
3 revisions
These instructions assume:
- you've followed the instructions on CarrierWave installation, and generating an
AvatarUploaderclass - already have a Devise model named
User - you wish to add an avatar to that model using CarrierWave, mounted on a column named
avatar
class AddUserAvatar < ActiveRecord::Migration
def self.up
add_column :users, :avatar, :string
end
def self.down
remove_column :users, :avatar
end
end- Add a
mount_uploaderline at the top of theUserclass - Add
:avatar,:avatar_cache, and:remove_avatarto the list of accessible attributes you already have generated by Devise. - Optional: Add avatar validations
This looks something like:
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :remember_me, :avatar, :avatar_cache, :remove_avatar
validates_presence_of :avatar
validates_integrity_of :avatar
validates_processing_of :avatar
endAssuming you have generated custom Devise views in the standard location, and that you are using Haml, this file is something like app/views/devise/registrations/new.html.haml. You need to:
- Add
:multipart => trueto the:htmlhash passed toform_for. - Add a
file_fieldnamed:avatarto upload an avatar - Add a
hidden_fieldnamed:avatar_cacheif you want to preserve uploads across form re-renders due to model validation failures
In Haml, this looks something like this:
= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:multipart => true}) do |f|
- # ...other form fields
= f.label :avatar do
= f.file_field :avatar
= f.hidden_field :avatar_cacheAssuming you have generated custom Devise views in the standard location, and that you are using Haml, this file is something like app/views/devise/registrations/edit.html.haml. You need to:
- Add
:multipart => trueto the :html hash passed toform_for. - Add an
image_tagif you want to display the current avatar - Add a
file_fieldnamed:avatarto upload a new avatar - Add a
hidden_fieldnamed:avatar_cacheif you want to preserve uploads across form re-renders due to model validation failures - Add a
check_boxnamed:remove_avatarif you want to support removing existing avatars.
In Haml, this looks something like this:
= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:method => :put, :multipart => true}) do |f|
- # ...other form fields...
- if current_user.avatar.url.present?
= image_tag(current_user.avatar.url)
= f.label :remove_avatar do
= f.check_box :remove_avatar
= f.file_field :avatar
= f.hidden_field :avatar_cache