TopperH
TopperH

Reputation: 2223

CanCan, restrict view action only for resources with a certain tag

I have a rails app that uses devise and cancan.

I have a Post resource that users (signed in or not) can read:

user ||= User.new
if user.has_role? :admin
  can :manage, :all
else
  can :read, Post
end

I use a tagging system to categorize posts and I want to create a tag called "restricted" whose show action is restricted to signed in users.

Here is how I call a post with the restricted tag:

@post.tags.find_by_name("restricted")

Should I use an if statement in the controller or somehow restrict the action in the ability.rb file?

Upvotes: 2

Views: 700

Answers (1)

Thanh
Thanh

Reputation: 8624

You can add below can :read, Post this code:

cannot :read, Post, tags: { name: "restricted" }

This restrict user not logged in can not read Posts have tag's name is "restricted".

Upvotes: 2

Related Questions