Reputation: 319
I have a sort action on a model called Chain. Following the sort example in Railscasts #147 Sortable Lists, the action is passed a :chain param that is an array of Chain ids:
def sort
params[:chain].each_with_index do |id, index|
Chain.update_all({position: index+1}, {id: id})
end
....
end
How can I use CanCan to make sure that the user has permission to update each of the individual chains that are in the params?
My :update Chain ability depends on whether the user has an admin role in the "Space" to which a chain belongs. Here's the definition:
can :update, Chain do |chain|
user.memberships.detect{|m| m.space == chain.space}.role.admin?
end
I'd like to see both the controller code and the Ability.rb code.
Upvotes: 0
Views: 114
Reputation: 3308
Model
class Ability
include CanCan::Ability
permitted_ids = Store.all.map &:id #you can store this in a db or whatever
def initialize(user)
permitted_ids.each do |i| #simply the can method has to run evaluate the Chain model against all your ids
can :update, Chain, id: i
end
end
end
Controller
def sort
params[:chain].each_with_index do |id, index|
authorize! :update, Chain, id: id
Chain.update_all({position: index+1}, {id: id})
end
end
Upvotes: 0