NoMethodError when using any?

I’m trying to use CanCan to an account scoped application. I wrote this method in my ability class:

roles = user.roles.find_by_account_id(

if roles.any? { |role| role.type == “Ownership” }

can :edit, Account


can :read, :all


The trouble is, “any?” works when “roles” is an array. Sometimes, however, user.roles returns only one object any other times my return nil. So calling roles.any? causes an error. How do I work around this?

My setup is User has_many Accounts through :roles, and vice-versa.


There are many ways to solve this problem.

One sugestion, maybe not the better: you can use the method kind_of?
to see if roles is a Array.

roles.kind_of? Array
(will return true)

Then, you could build your logic upon this.

Best Regards,

Another way would be to change:

roles = user.roles.find_by_account_id(


roles = user.roles.where(account_id:

I forgot to mention that where() returns an array where as find_by_foo returns a single object unless there are multiple objects…

Nice, I forgot about that too...