开发者

Rails 3: HABTM, destroy and before_destroy callback

If I have read the rails guides correctly, a before_destroy callback that returns false will stop the object being destroyed by issuing a rollback command.

However, while the object itself is not being removed I'm finding that all objects in a HABTM relationship on that object are. How can I stop this from happening?

Here's the appropriate code block:

class UserGroup < ActiveRecord::Base

  # Associations
  has_and_belongs_to_many :users, :join_table => "user_group_membership"

  a开发者_运维技巧ttr_protected :is_default

  # Callbacks
  before_destroy :destroy_associations

  def destroy_associations
    if self.is_default?
      errors.add(:base,"You can't delete the default")
      return false
    end
    self.users.clear
  end
end

Now when I call destroy on a "is_default" group, I get the correct error message added to the base, the UserGroup object is NOT destroyed but every association in the :users collection is cleared.

I know that the code "self.users.clear" is never reached - so why am I losing my HABTM collection?

If it helps, I am using JRuby 1.9 with an mssql database.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜