Francesco Meli
Francesco Meli

Reputation: 2700

Create authorization using CanCanCan gem and ActiveAdmin

I created some rules and one of them is the following:

can :create, Ticket, { author_id: user.id }

This should allow the currently authenticated user to create tickets only when author_id is equal the user's id.

From rails console I can test that my rule works fine:

my_user.can? :create, Ticket.new(author: my_user)      # returns true
my_user.can? :create, Ticket.new(author: another_user) # returns false

Considering that I'm using ActiveAdmin, I now need to use my authorization rules with it by using its ActiveAdmin::AuthorizationAdapter.

One problem I am facing is that whenever I create a "New Ticket" I get access denied.

I doubled checked what condition is failing and it seems that AA asks for the following:

my_user.can? :create, Ticket.new # which returns false!

When I believe it should ask for the following instead:

my_user.can? :create, Ticket # which returns true!

Ticket.new has all parameters set to nil:

<Ticket author_id: nil, ..., created_at: nil, updated_at: nil>

that is why my CanCanCan hash condition is failing (author_id = nil is not valid, it should be user_id instead).

Is there a a possibile fix for this? Maybe I'm setting my CanCanCan rule in the wrong way?

ActiveAdmin is also offering a CanCanCan adapter out of the box so I'm wondering how they could have overlooked this.

Upvotes: 0

Views: 451

Answers (1)

agbodike
agbodike

Reputation: 1846

Based on answer to a similar question:

ActiveAdmin.register Ticket do
  before_build do |ticket|
    ticket.author = current_user
  end
end

This sets the author while creating the new object, which qualifies it to be accessible as configured in the CanCanCan abilities.

@GoGoCarl commented with the relevant question above, but I've modified for the question asked here. Original answer:

https://stackoverflow.com/a/28738827/3353794

Upvotes: 1

Related Questions