I have a non-restful controller that I am trying to use the cancan authorize! method to apply permissions to.
I have a delete_multiple action that starts like so
def delete_multiple
@invoices = apparent_user.invoices.find(params[:invoice_ids])
I want to check that the user has permission to delete all of these invoices before proceeding. If I use
authorize! :delete_multiple, @invoices
permission is refused. My ability.rb includes the following
if user.admin?
can :manage, :all
elsif user.approved_user?
can [:read, :update, :destroy, :delete_multiple], Invoice, :user_id => user.id
end
Is it a matter of looping through my array and calling authorize individually or is there a smarter way of doing things? I'm starting to feel like doing authorizations would be easier manually than by using cancan for a complicated non-restful controller (although I have plenty of other restful controllers in my app where it works great).
A little late in here but you can write this in your ability class
EDIT
This can be written also as:
It seems that
authorize!
only works on a single instance, not an array. Here's how I got around that with Rails 3.2.3 and CanCan 1.6.7.The basic idea is to count the total records that the user is trying to delete, count the records that are
accessible_by (current_ability, :destroy)
, then compare the counts.If you just wanted an array of records that the user is authorized to destroy, you could use the array returned by
accessible_by (current_ability, :destroy)
. However I'm usingdestroy_all
, which works directly on the model, so I wound up with this count-and-compare solution.It's worthwhile to check the development log to see how the two
SELECT COUNT
statements look: the second one should addWHERE
phrases for the authorization restrictions imposed by CanCan.My example deals with deleting multiple messages.
ability.rb
messages_controller.rb