简体   繁体   中英

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 aa 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM