0

Is there any easy tutorial for roles? I found that Devise is great & easy solution for authorization. And then when it comes to Cancan with Rolify there's a confusion eclipse for beginners like me.

Currently I'm defining roles in ability.rb:

if user.has_role? :admin
  can :manage, :all
else
  can :read, :all
end

And then, in the controller, I'm checking like in this example:

def destroy
 ability = Ability.new(current_user)
 if ability.can? :delete, :all then
   @post = Post.find(params[:id])
   @post.destroy
 end

 respond_to do |format|
   ...
end

My question is - I have a strange feeling the check if ability.can? :delete, :all then is redundant in this example. So is my code ok or I really got it wrong? Thanks

valk
  • 9,363
  • 12
  • 59
  • 79

2 Answers2

1

It would make more sense to check if they can delete the post in question. An admin may be able to delete anything, but a normal user would only delete content they own.

@post = Post.find(params[:id])
authorize! :delete, @post

I'd also suggest you spend some time reading cancan's documentation, as your code doesn't really match up.

DVG
  • 17,392
  • 7
  • 61
  • 88
0

I think your "destroy" method can be like:

def destroy
 @post = Post.find(params[:id])
 if can? :delete, @post then 
   @post.destroy
 end

 respond_to do |format|
   ...
end

Because in cancan's doc:

The current user’s permissions can then be checked using the can? and cannot? methods in the view and controller.

Jacky
  • 8,619
  • 7
  • 36
  • 40