When overriding the registration controller from devise, is it possible to access the newly created user on the create action?

StackOverflow https://stackoverflow.com/questions/19140748

Question

I'm trying to create a folder right after a user registers, so I override the create action on the registration controller (devise) but I don't know how to access the newly created user in order to create the folder with it's name to upload files later.

So far I've got this:

class RegistrationsController < Devise::RegistrationsController

  def new
    super
  end

  def create
    super
    create_folder
  end
  
  def update
    super
  end
  
  def create_folder
    path =  Pathname.new(':rails_root/tmp/')
    directory_name = ":current_user"
    Dir.mkdir(path, directory_name) unless File.exists?(directory_name)
  end
end

routes.rb

 devise_for :users, :controllers => {:registrations => "registrations"}

I followed this to override the registration controller.

  1. Should I leave it there or move it to the create action? Instead of using a method
  2. is that the right way to access the current user?
  3. Maybe instead of registration it's better to do it on sign in?

I'd appreciate any help I can get.

Was it helpful?

Solution

You should really be accomplishing this functionality in an after_filter to your action, rather than in the action itself:

class RegistrationsController < Devise::RegistrationsController
  after_filter :create_folder, :only => :create

  protected

  def create_folder
    path =  Pathname.new(Rails.root.to_s + '/tmp/') #=> Note 1
    directory_name = resource.id.to_s                #=> Note 2
    Dir.mkdir(path + directory_name)                #=> Note 3
  end
end

Notes:

  1. Your syntax for retrieving the project root is incorrect. :rails_root can't be interpolated from within single quotes - and it doesn't exist, anyways. Try Rails.root.to_s instead.
  2. ":current_user" is simply a string that will attempt to name the directory :current_user, which is neither dynamic nor valid. Because your Devise controller has access the the current resource (which in this case, represents the current_user), retrieve the resource.id and use it instead.
  3. Concatenate the path and directory_name together with +, not ,. There's no need for the unless conditional, since you're presumably only creating the new folder upon creation of a new user, and each user has a unique id.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top