Allowing admins to add users with Devise

前端 未结 3 1662
误落风尘
误落风尘 2020-12-16 23:03

I\'m trying to make it so only admins can add uses with devise. I\'ve gotten it mostly working however now when I\'m logged in as an admin and submit the sign up form it kic

3条回答
  •  [愿得一人]
    2020-12-16 23:54

    Using Rails 4.2.6 here (my model is User instead of Editor). The following solution bypasses (I think) any devise actions that may interfere with new User creation by the admin:

    Add this action to the Users controller:

    def savenew
      User.create_new_user(user_params)
      redirect_to action: 'index'
    end
    

    Add this private method to the Users controller if it does not exist:

    private
    
    def user_params
      params.require(:user).permit(:email, :password,      
                                   :password_confirmation)
    end
    

    Add this to config/routes.rb:

    match '/savenew', to: 'users#savenew', via: :post
    

    Add this class method to the User model:

    def self.create_new_user(params)
      @user = User.create!(params)
    end
    

    I don't have a separate Admin class in my application. Instead, I defined an admin attribute for Users and check for it with a :validate_admin before_action filter in the UsersController.

    I wanted to be able to create a new user from the :index view, so I added a button:

    <%= button_to 'New User', '/new_user', class: 'btn btn-primary',
                              method: :get %>
    

    You might have to tweak the above solution if you have any after_create actions in the User model (e.g. sending a welcome email).

提交回复
热议问题