mongoid/mongoid — Issue #1354: :dependent => :restrict For Associations
Author: tyok
Created: 2011-10-18 14:53:25+00:00
State: open

I think it would be nice if mongoid supports `:dependent => :restrict` for associations. Currently ActiveRecord has it, e.g.:

``` ruby
class Post < ActiveRecord::Base
has_many :comments, :dependent => :restrict
end
```

It would raise an error unless the value of `#comments` is `nil`.

Currently I use a hack which is roughly like this:

``` ruby
module Mongoid
module Restrictable extend ActiveSupport::Concern
module ClassMethods

def restrict_destroy_if_has(*attrs)
attrs.each do |attr|
before_destroy do |post|
raise "Cannot destroy" unless post.send(attr).nil?
end
end
end

end
end
end
```

Which I can use by including it in a mongoid model:

``` ruby
class Post
include Mongoid::Document
include Mongoid::Restrictable
has_many :comments
restrict_destroy_if_has :comments
end
```

Any thought on this?