我有这个型号:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
before_destroy do |u|
if u.superadmin? and User.joins(:roles).where(:roles => {:superadmin => true}).count == 1
u.errors.add(:base, "cannot delete last admin user")
return false
end
return true
end
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
当我尝试删除最后一个superadmin时,before_destroy回调会添加到errors数组并返回false。我在控制器中收到错误信息,一切似乎都没问题。
Rails3 从联接表中删除我的记录。的为什么?我返回false,因为我返回false,不继续删除。这是日志:
SQL (0.2ms) SELECT COUNT(*) FROM "users" INNER JOIN "roles_users" ON "roles_users"."user_id" = "users"."id" INNER JOIN "roles" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."superadmin" = 't'
AREL (0.4ms) DELETE FROM "roles_users" WHERE "roles_users"."user_id" = 1 AND "roles_users"."role_id" IN (1, 4)
Organization Load (0.4ms) SELECT * FROM "organizations" INNER JOIN "organizations_users" ON "organizations".id = "organizations_users".organization_id WHERE ("organizations_users".user_id = 1 )
感谢您的帮助。
答案 0 :(得分:2)
这看起来像这个rails错误,如果你使用旧的Rails版本(它应该在Rails 3.0.6 AFAIK中解决):