Fernando Maymone
Fernando Maymone

Reputation: 355

CanCanCan view only if has attribute

Im using CanCanCan to manage my authorizations pages.

This is how is set my Abilities page:

class Ability
 include CanCan::Ability
 def initialize(user)

#return if user.nil?
if user.nil? 
  can :read, User
  can :read, Talent, {is_major: false}
else

A User has_one Talent. And a Talent has a method called: is_major. This method checks if the talent have more then 18 years old.

I want that, a User that is not logged in on the app, can only read a Talent if this Talent is_major.

How can I setup it on CanCanCan?

Upvotes: 0

Views: 327

Answers (2)

JoeyParis
JoeyParis

Reputation: 27

You'll want to define the ability with block syntax since is_major? is a model method.

can :read, Talent do |talent|
    talent.is_major?
end

Upvotes: 0

Fernando Maymone
Fernando Maymone

Reputation: 355

The problem here was only a sintax:

If I add:

if user.nil? 
  can :read, User
  can :read, Talent, is_major?: true
else

It works.

Upvotes: 0

Related Questions