如何在注册Rails3和Devise后添加回调 [英] How to add callback after registration with Rails3 and Devise

查看:177
本文介绍了如何在注册Rails3和Devise后添加回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何添加回调以为注册用户创建帐户。

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

设计文件(registrations_controller.rb)在控制器/设计
我的用户模型有has_many:accounts关系(和帐户模型有belongs_to: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?)

那么,如何自动创建一个具有正确user_id的新帐户?

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

提前感谢。 / p>

Thanks in advance.

推荐答案

您可以覆盖devise的注册控制器,使用过滤器添加回调来创建帐户。记住命名文件registrations_controller.rb

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

然后在你的routes.rb中告诉devise使用覆盖控制器注册

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

devise_for :users, controllers: { registrations: 'registrations'}

这篇关于如何在注册Rails3和Devise后添加回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆