创建钩子后设计

ed1*_*d1t 12 devise ruby-on-rails-3

是否有我可以实现的钩子或回调,以便在创建用户之后,我想调用一些自定义代码?

我在用户模型中尝试了after_confirmation钩子但是没有用.

Rya*_*igg 19

使用after_createRails提供的标准回调.

class User < ActiveRecord::Base
  after_create :do_something

  def do_something
    puts "Doing something"
  end
end
Run Code Online (Sandbox Code Playgroud)


eco*_*gic 6

如果要处理所创建模型的内部状态,则使用回调是完全合法的。

创建后User,我需要创建默认的Team。最好避免使用回调来处理其他对象

“ after_ *”回调主要用于保存或持久化对象。一旦对象被保存,对象的目的(即责任)就已经实现,因此我们通常会看到回调超出了其责任范围,这就是我们遇到问题的时候。

从这篇很棒的博客文章中

在这种情况下,最好对控制器采取行动,您可以在其中直接添加功能或委托给服务以获取更干净的解决方案:

# shell
rails g devise:controllers users

# config/routes.rb
devise_for :users, controllers: { registrations: "users/registrations" }

# app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
  after_action :create_default_team, only: :create

  private

  def create_default_team
    Team.create_default(@user) if @user.persisted?
  end
end
Run Code Online (Sandbox Code Playgroud)


mb2*_*b21 6

我正在使用带有Devise 3.5的Rails 4,confirmable并且由于各种惊喜而不得不这样做.

class User < ActiveRecord::Base
  # don't use after_create, see https://github.com/plataformatec/devise/issues/2615
  after_commit :do_something, on: :create

  private

    def do_something
      # don't do self.save, see http://stackoverflow.com/questions/22567358/
      self.update_column(:my_column, "foo")
    end
end
Run Code Online (Sandbox Code Playgroud)