Adding a helper method for current_ability #361

Closed
BaylorRae opened this Issue May 9, 2011 · 2 comments

3 participants

@BaylorRae

I'm using cancan in my project and I needed a way to limit the results in a collection_select field. After looking through the docs I learned I could use Model.accessible_by(current_ability). But this doesn't work in the view, only the controller. So after looking through the source I found the current_ability method and copied it over to my application helper and it's now working.

My reasoning for this "issue" is to hopefully have someone add this to the gem if it's wanted. I'm new to ruby/rails and I may have duplicated code so please forgive me if I have.

@ryanb
Owner

Thanks for the feedback, this will be a simple fix. I'll mark it to be added.

@jgkite

For now, you shouldn't need to copy the current_ability method into your application helper to get the same functionality. Assuming that you have a current_user (which CanCan requires) and that you have set up the ability method in your User model, the following should work in your views and helpers:

Model.accessible_by(current_user.ability)

I also have a helper method set up to remove some of the complexity from the view. Following from your Model.accessible_by example above, this would translate to:

def models_to_options_for_select
  Model.accessible_by(current_user.ability).collect {|m| [ m.name, m.id ] }
end
@ryanb ryanb closed this in 4e4c5a9 May 17, 2011
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment