Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add callback after registration with Rails3 and Devise

How to add a callback to create an account for the registered user.

Devise files (registrations_controller.rb) are under controllers/devise My user model has has_many :accounts relationship (and the account model has belongs_to :user)

First I don't know where to add the callback (what file?)

Then, how to automatically create a new account with the right user_id of the registered user?

Thanks in advance.

like image 938
Olivier Avatar asked Jan 15 '11 23:01

Olivier


1 Answers

You can override devise's registration controller, add callback to create account using filters. Remember to name the file registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  after_filter :add_account 

  protected

  def add_account
    if resource.persisted? # user is created successfuly
      resource.accounts.create(attributes_for_account)
    end
 end
end

then in your routes.rb tell devise to use overrided controller for registration

devise_for :users, controllers: { registrations: 'registrations'}
like image 135
Naveed Avatar answered Oct 07 '22 09:10

Naveed