Admin Change Approval Status of User - Rails + Devise + Cancancan

陌路散爱 提交于 2019-12-02 11:54:10

I spent a lot of time trying to solve this and didn't find any definitive, end-to-end complete examples online so I'm putting everything below so any new users to RoR/Devise hopefully won't have same problems.

Assuming Devise is on the User model. Ensure your Cancancan is setup accordingly. Something similar to this:

models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user)
    # Define abilities for the passed in user here. For example:
    #
    current_user ||= User.new # guest user (not logged in)
    if current_user.admin
      can :manage, :all
    else
      can :manage, User, id: user.id
    end
 end
end

Follow the steps in here

He mentions have an 'admin-accessible only' page. In case someone's not sure how to do this:

class UsersController < ApplicationController
  before_action :admin?, only: :index

  def index
    if params[:approved] == false
      @users = User.where(approved: false)
    else
      @users = User.all
    end
  end

private
  def admin?
    redirect_to '/login' unless current_user.admin == true
  end

end

Replace this line (I use .erb not .haml as he does in the link) %td= link_to "Edit", edit_user_path(user) with this: <%= User.approved %>

          <td>
            <% if !User.approved %>
              <%= link_to "Approve User", user_path(:id => user.id, "user[approved]" => true), :method => :patch, class: "btn btn-success" %>
            <% else %>
              <%= link_to "Unapprove User", user_path(:id => user.id, "user[approved]" => false), :method => :patch, class: "btn btn-danger" %>
            <% end %>
          </td>

This essentially gives you a button that when clicked, will approve the user and visa-versa. The key here that tripped me up for days is that a) You have to ensure that your form (in this case, the link_to hits the Users controller and NOT the RegistrationsController#update method.

I know some online links gave instructions to create a Registrations model and changing routes, overriding models, etc.

Honestly, my final solution didn't need any of that. Hope this helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!