I followed this link to figure out how to have an admin approve a new user. I have an approved
attribute on my User
model that is a boolean.
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 %>
<% 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 %>
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!