Search code examples
ruby-on-railsdevisecancan

Can't use methods in the application helper for cancan ability.rb


I'm using Devise and cancancan. In my application helper I have -

def is_part_of_team?(book)
    on_team = false
    book.contributions.each do |contribution|
        if contribution.user == current_user
            on_team = true
        end
    end
    if book.user == current_user
        on_team = true
    end
    return on_team
end

and in ability.rb I have -

include ApplicationHelper
...
can :update, Book do |book|
  is_part_of_team?(book)
end

... this throws the error -

undefined local variable or method `current_user' for #<Ability...

There are probably better ways of doing this, but I just wondered why cancan does not like current_user within the application helper. Why is this? I use this function from views and it's all dandy.


Solution

  • My approach was bad altogether.

    Instead of all that code in the helper, I hadn't understood that I could use this -

    book.contributions.where(user_id: user.id).any?
    

    ...to get exactly the same result. This means in ability.rb I can have this -

      can :update, Book do |book|
        (book.try(:user) == user) || book.contributions.where(user_id: user.id).any?
      end