Search code examples
ruby-on-rails-3cancan

Using CanCan in Ruby on Rails and want to use an 'or' condition in the can definition


I have CanCan setup in RoR and it works fine when I have:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new

    can :read, List, :user_id => user.id

  end
end

What I want to do is specify an "or" condition where either the user_id matches or else it has an access level of 'public'

can :read, List, (:user_id => user.id || :access => 'public')

But that of course does not work.


Solution

  • You can use a block, as mentioned in the documentation.

    can :read, List do |l|
      l.user_id == user.id || l.access == 'public'
    end