Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Specify cancan attributes_for conditions even when using block syntax

View ability.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# A quick hack that shows how to add a hash
# of conditions to cancan rules when the block syntax is used
 
# (sadly, you can't use the conditions and the block syntax at the time, so
# when you need to use a block you have to give up the conditions. until now!)
 
class Ability
include CanCan::Ability
 
def initialize(user)
 
# some rules here ...
 
can :create, Pizza do |pizza|
user.recipes.include?("pizza") ||
user.appliances.include?("microwave")
end
 
rules.last.instance_variable_set("@conditions", { user_id: user.id })
 
#...now when PizzaController#new builds a Pizza via load_resource
#that pizza's user_id will automatically be populated
#just as if you had written the rule as:
# can :create, Pizza, user_id: user.id
 
# more rules here...
end
end

Yay Ruby!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.