Rails - defining cancan ability using associations

杀马特。学长 韩版系。学妹 提交于 2021-02-08 07:05:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!