hellion
hellion

Reputation: 4850

Rails - defining cancan ability using associations

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?

Upvotes: 1

Views: 1391

Answers (2)

smoyth
smoyth

Reputation: 709

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.

Upvotes: 2

Andrew
Andrew

Reputation: 43153

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.

Upvotes: 3

Related Questions