Created
May 26, 2012 06:33
-
-
Save joshed-io/2792585 to your computer and use it in GitHub Desktop.
Specify cancan attributes_for conditions even when using block syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yay Ruby!!