Search code examples
ruby-on-railsrails-admin

after_create trigger just if is called from rails_admin?


Hi I have a custom after_create action in my model, but I just want to trigger it if the object was created from Rails_admin, is there any way to do that?


Solution

  • Sure. Add a virtual attribute to the model, set its value in the controller based on some attribute sent via Rails_admin or whether the current_user is an admin, then check for it in your custom callback. For example, if your model is a 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
    

    Add a param to the data coming from Rails_admin. You can skip this if you have some type of 'admin' role on the current user.

    Then in your controller that handles the creation of the object, set the is_admin attribute on your model instance like:

      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