2014-02-11 72 views
1

我的用戶模型中的after_create回調中有一個默認角色分配,但總是在數據庫中創建重複角色。是使用after_create回調時使用rolify添加的重複角色

我的用戶模型的適用部分如下

class User < ActiveRecord::Base 

    include RailsSettings::Extend 
    after_create :assign_basic_role 

    rolify 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    has_many :locations, as: :locatable 
    has_many :prospects, as: :prospectable, :dependent => :destroy 
    has_many :deals, :through => :prospects 
    belongs_to :agency 

private 
    def assign_basic_role 
    self.add_role :basic, self.agency 
    end 
end 

而且從控制檯

Role Load (0.4ms) SELECT "roles".* FROM "roles" WHERE "roles"."name" = 'basic' AND "roles"."resource_type" = 'Agency' AND "roles"."resource_id" = 11 ORDER BY "roles"."id" ASC LIMIT 1 
    Role Exists (0.5ms) SELECT 1 AS one FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND "roles"."id" = 12 LIMIT 1 [["user_id", 144]] 
    (0.4ms) SELECT "roles".id FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 [["user_id", 144]] 
    Role Load (0.3ms) SELECT "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT 1 [["id", 12]] 
    Role Load (0.4ms) SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 [["user_id", 144]] 
    (0.3ms) INSERT INTO "users_roles" ("user_id", "role_id") VALUES (144, 12) 
    (0.2ms) INSERT INTO "users_roles" ("user_id", "role_id") VALUES (144, 12) 
+0

我與rolify作者分享了這個問題:https://github.com/EppO/rolify/issues/228 – etc

回答

1

這是一個錯誤的肯定。給我造成了很多煩惱。下面是我周圍如何到達:

的 代替

在模型中,
after_create :create_a_role 

after_commit :create_a_role, on: :create 

沒有更多的重複。好極了!

相關問題