after_create 仅在从 rails_admin 调用时触发?

after_create trigger just if is called from rails_admin?

您好,我的模型中有一个自定义 after_create 操作,但我只想在对象是从 Rails_admin 创建的情况下触发它,有什么方法可以做到这一点吗?

当然可以。向模型添加虚拟属性,根据通过 Rails_admin 发送的某些属性或 current_user 是否为管理员在控制器中设置其值,然后在自定义回调中检查它。例如,如果您的模型是用户:

class User < ApplicationRecord
  attr_accessor :is_admin #Virtual Attribute
  after_create :my_custom_callback

  
  def my_custom_callback
    unless self.is_admin.blank?
      #Handle callback logic
    end
  end
end

为来自 Rails_admin 的数据添加一个参数。如果您对当前用户具有某种类型的 'admin' 角色,则可以跳过此步骤。

然后在处理对象创建的控制器中,在模型实例上设置 is_admin 属性,例如:

  def create
    @user = User.new(blah blah blah)
    unless params[:rails_admin].blank? # Ideally current_user.admin would be better
      @user.is_admin = true
    end
    @user.save
  end

您可以编写自定义回调,例如,

class Admin < ApplicationRecord
  
  after_create :custom_callback
  
  def custom_callback
    if self.user_type == "ADMIN"
      # Add rails admin login here
    end
  end
end

# Call this from controller

def create_admin
  Admin.create!(user_type: "ADMIN", other_details: "")
end

> if can manage user_type column in DB then you can directly call using self otherwise you can add attr_reader in you model like,
attr_reader :user_type
More about on attr_reader refer this [1]

  [1]: https://apidock.com/ruby/Module/attr_reader