Skip to content

CanCan populating the primary key of User #1880

@zoer

Description

@zoer

Setup:
Rails 4.0.2
Mongoid 4
CanCan 1.6.10

Objective
Change user2 email to superman@bb.cc

class Ability
  include CanCan::Ability

  def initialize(user)
    can :update, User, id => user.id # if current_user

    if admin?
        can :update, User
    end
  end

  #...
end
class User
  include Mongoid::Document

  field :email
  field :name
  # ...
end

We have 2 records in DB
Currently logged user with admin rights:

{
  "_id" : ObjectId("52c1f3646d6b005564000001"),
  "name": "admin",
  "email", "aa@bb.cc",
  ...
}

User for edit

{
  "_id" : ObjectId("52c1f3646d6b005564000002"),
  "name": "user2",
  "email", "bb@bb.cc",
  ...
}

When we are trying to change email of user2 through the rails_admin, changed admin email instead of user2. When I dive to rails_admin edit action code, I discovered for this lines:

@authorization_adapter && @authorization_adapter.attributes_for(:update, @abstract_model).each do |name, value|
  @object.send("#{name}=", value)
end

evaluate to this:

# @object.id is "52c1f3646d6b005564000002"
@object.send("id=", "52c1f3646d6b005564000001") # set the current logged user.id

because I have cancan rule can :update, User, id => user.id

as a workaround I just change rule to this:

can :update, User do |object|
   object.id == user.id
end

and all work as expected.

I think that you should know about this behavior.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions