Search code examples
ruby-on-rails-4activeadminstrong-parameters

permit_params not working for custom create action


I can't understand why permit_params wont work with custom create action.

For example lets take basic AdminUser resource.

By default all is working fine. We have:

ActiveAdmin.register AdminUser do
  permit_params :email, :password, :password_confirmation

  form do |f|
    f.inputs "Admin Details" do
      f.input :email
      f.input :password
      f.input :password_confirmation
    end
    f.actions
  end
end

But as soon we add custom create for some reasons permit_params wont work anymore.

ActiveAdmin.register AdminUser do
  permit_params :email, :password, :password_confirmation

  form do |f|
    f.inputs "Admin Details" do
      f.input :email
      f.input :password
      f.input :password_confirmation
    end
    f.actions
  end

  controller do
    def create
      AdminUser.create(params[:admin_user])
      do_some_magic_stuff_here
      redirect_to backend_admin_users_path, notice: 'Custom create'
    end
  end
end

I got error "ActiveModel::ForbiddenAttributesError" in line "AdminUser.create(params[:admin_user])"

Tried many possible solutions and only one worked for me, but i really don't like this:

def create
  AdminUser.create(params[:admin_user].permit(:email, :password, :password_confirmation))
  do_some_magic_stuff_here
  redirect_to admin_admin_users_path, notice: 'Custom create'
end

I can't understand why i can't get to work default way as it should work:

def admin_user_params
  params.require(:admin_user).permit(:email, :password, :password_confirmation)
end

Can someone explain me please what is happening here? Any nice way to have custom actions work with permit_params?


Solution

  • permit_params is just part of the AA DSL that defines a method called permitted_params, which in turn is called from the create and update actions. Try this:

    permit_params :email, :password, :password_confirmation
    
    controller do
      def create
        @admin_user = AdminUser.create(permitted_params)
        do_some_magic_stuff_here
        redirect_to backend_admin_users_path, notice: "Custom create"
      end
    end
    

    permit_params is really just a simpler form of the old, but still valid way of enabling strong parameters:

    controller do
      def permitted_params
        params.permit admin_user: [:email, :password, :password_confirmation]
      end
    end