0
votes

I just set up Devise with Cancan for user roles. I think I'm on the right track, but I just ran into a situation where I think I'm missing something small.

I want any user with role :admin to be able to edit the profiles/roles of every other user. I have the routes set up right, but when I click on the links for other users, I get redirected.

_user.html.erb

<% @users.each do |user| %>
    <li>
        <%= gravatar_for user, size: 52 %>
        <%= link_to user.name, user %>
        <% if can? :assign_roles, @user %>
            | <%= link_to "delete", user, method: :delete, confirm: "Delete user?" %>
            | <%= link_to "edit", edit_user_path(user) %>
        <% end %>
    </li>
<% end %>

users_controller.rb ... def edit @user = User.find(params[:id]) end

  def update
    authorize! :assign_roles, @user if params[:user][:assign_roles]
    if @user.update_attributes(params[:user])
      flash[:success] = "Profile updated"
      sign_in @user
      redirect_to @user
    else
      render 'edit'
    end
  end

ability.rb

def initialize(user)
     can :assign_roles, User if user.admin?
     can :manage, :all if user.is? :admin
end

I've been changing this code around all day, I might even be going in circles.

Any help would be greatly appreciated.

1

1 Answers

1
votes

I figured it out. Even though I was able to limit the html/css with the logic shown about, I was not able to limit model/controller interaction. I have multiple controllers, and the one I was dealing with had no authentication check. So in other words, I added

 before_filter :authenticate_user!

to my users_controller.rb file, and now it knows that I'm an admin, and what that means. I just added this on a whim, but everything I've learned about Devise/Cancan so far is from the wiki:

https://github.com/ryanb/cancan/#wiki-readme