Skip to content

Instantly share code, notes, and snippets.

@joshed-io
Created May 26, 2012 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshed-io/2792585 to your computer and use it in GitHub Desktop.
Save joshed-io/2792585 to your computer and use it in GitHub Desktop.
Specify cancan attributes_for conditions even when using block syntax
# 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
@loveybot
Copy link

Yay Ruby!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment