I have got this model:
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
When I try to delete last superadmin, the before_destroy callback adds to errors array and return false. I get the error message in the controller, everything seems to be fine.
Except Rails3 deletes me record from the join table. Why? I returned false, as I return false it should not proceed with the deletion. Here is the log:
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 )
Thanks for help.
This seems like this rails error, if you use older Rails version (it should be solved in Rails 3.0.6 AFAIK):
https://rails.lighthouseapp.com/projects/8994/tickets/6191-habtm-association-is-being-destroyed-before-the-before_destory-callbacks-are-executed