我有這種模式:Rails3中刪除我HABTM記錄時回調返回false
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
當我嘗試刪除最後一個超級管理員,在before_destroy回調增加錯誤排列並返回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)
感謝您的幫助。
我看到了很多網絡「內容」提示返回假的行爲並不像人們期望的那樣。這些相同的消息來源表明,重定向或渲染之前的過濾器是解決這個問題的「Rails方式」,但我對此沒有任何意見。 – jaydel