问题
When defining abilities in the cancan Ability class...
Is this:
can :manage, Area, :location => { :company => { :manager => { :user_id => user.id } } }
The same as this:
can :manage, Area do |area|
area.location.company.manager.user_id == user.id
end
I'm just trying to better understand defining an ability without using a block. Is one way better (maybe faster) than the other?
回答1:
The two should be the same, however the second way is much clearer if anyone else is reading your code. I would definitely recommend using the second way. If what bothers you is taking up multiple lines, you could just write:
can( :manage, Area ) {|area| area.location.company.manager.user_id == user.id }
That's possibly cleaner (when stacked with a bunch of other rules) than either other option.
回答2:
As it says here:
https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks#fetching-records
the big advantage of using a block is that it accessible_by will still work. If you use a block and also want to use accessible_by you need to add in the SQL where clause manually, which is not quite DRY and to be avoided if possible IMO.
来源:https://stackoverflow.com/questions/12169728/rails-defining-cancan-ability-using-associations