How to add callback after registration with Rails3

2019-02-09 06:27发布

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.

4条回答
Melony?
2楼-- · 2019-02-09 06:58

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
查看更多
何必那么认真
3楼-- · 2019-02-09 07:04

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楼-- · 2019-02-09 07:16

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.

查看更多
Bombasti
5楼-- · 2019-02-09 07:21

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'}
查看更多
登录 后发表回答