Reputation: 75
The problem is I have two models - Project and Ticket (which belongs to project). I want to deny access to tickets creation upon Project expiration (i.e. I want user couldn't create new ticket for expired project).
How can I deny the creation of a ticket for user in CanCan Ability? Something like
if user.role? :superuser
can :read, :all
can :create, Ticket do |ticket|
ticket.project.expired?
end
end
The problem is "project" method is not defined anywhere. I would much appreciated some help.
Upvotes: 0
Views: 88
Reputation: 10898
You simply need to test whether the potential ticket's project has expired before granting permission. The key being that permission is being granted against the project, not the ticket.
For this I'd probably define a special ability ...
if user.role? :superuser
can :read, :all
can :create_ticket_for_project, Project do |project|
!project.expired?
end
end
Then use that in your controller:
authorize! :create_ticket_for_project, @project
Upvotes: 2