0

我只是想在用户注册时创建另一条记录。我认为以下是 Clearance 触及我的应用程序的唯一地方,不计算视图。

class ApplicationController < ActionController::Base
  include Clearance::Controller
  before_action :require_login
  .
  .
  .
end

class User < ActiveRecord::Base
  include Clearance::User
  has_many :received_messages, class_name: 'Message', foreign_key: :receiver_id
  has_one :privilege
end
4

1 回答 1

2

您想要after_create(或者可能是before_create,或其他一些钩子,取决于您的语义),它由 Rails 提供,独立于 Clearance。它允许您声明一个在User创建记录后运行的方法,并且该方法可以创建您希望存在的其他对象。

class User < ActiveRecord::Base
  after_create :create_other_thing

  private

  def create_other_thing
    OtherThing.create(other_thing_attributes)
  end
end

请注意after_create,在与您的创建相同的事务中运行User,因此如果在 期间出现异常OtherThing.create,它和 都User将被回滚。

查看Active Record 回调以获取有关 ActiveRecord 生命周期挂钩如何工作的完整详细信息。

于 2016-02-10T03:44:31.297 回答