问题
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.
回答1:
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'}
回答2:
Here's a thread on the google group that answers your question:
http://groups.google.com/group/plataformatec-devise/browse_thread/thread/6fc2df8d71f8b2f0
Basically it recommends just adding a standard rails "after_create" method to your user model to run the code you need.
回答3:
I'm using both approaches.
after_create in the model to create associated data and
after_filter :send_notification_mailer, only: :create
In the RegistrationsController (same as @naveed)
because in the after_create callback I was receiving the error exception
ActiveJob::DeserializationError: Couldn't find User with id
when sending with Active Job the confirmation email in background with sidekiq because the user it was not persisted sometimes.
回答4:
First, open your version of devise with bundle open devise
. Check out the app/controllers/devise/registrations_controller.rb. You will probably see a method called in the create method when a user successfully registers. For my version (3.5.2) it is sign_up
.
In routes, you'll need
devise_for :users, :controllers => { :registrations => "registrations" }
The you can define your own RegistrationsController like so:
class RegistrationsController < Devise::RegistrationsController
protected
def sign_up(_resource_name, user)
super
# do your stuff here
end
end
来源:https://stackoverflow.com/questions/4702806/how-to-add-callback-after-registration-with-rails3-and-devise