这很奇怪。我在我的 rails 3.2 应用程序中使用 Rolify + CanCan + Devise。我的用例很简单。我希望用户一次只有一个角色,因此要更改角色,我会执行以下操作:
user.remove_role "admin"
user.add_role "associate"
对我来说奇怪的是,当我这样做时,角色“admin”会从 Roles 表中删除。为什么会这样?我不想完全消除这个角色,只是从用户那里获得一个给定的角色。我究竟做错了什么?
这是SQL。注意最后一个 delete from roles 语句:
3] pry(main)> u.remove_role "sub_admin"
Role Load (0.1ms) SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = 2 AND "roles"."name" = 'sub_admin'
(0.0ms) begin transaction
(0.3ms) DELETE FROM "users_roles" WHERE "users_roles"."user_id" = 2 AND "users_roles"."role_id" IN (2)
(1.9ms) commit transaction
User Load (0.1ms) SELECT "users".* FROM "users" INNER JOIN "users_roles" ON "users"."id" = "users_roles"."user_id" WHERE "users_roles"."role_id" = 2
(0.0ms) begin transaction
SQL (2.1ms) DELETE FROM "roles" WHERE "roles"."id" = ? [["id", 2]]
(0.6ms) commit transaction