mongoid/mongoid — Issue #1675: validates_presence_of association fails when re-saving a model
Author: behrangsa
Created: 2012-02-05 08:44:34+00:00
State: open

Having two models `Post` and `Tag`:

```ruby
class Post
include Mongoid::Document

field :title, type: String

has_many :tags

validates_presence_of :tags
end

class Tag
include Mongoid::Document

field :title, type: String

belongs_to :posts
end
```

This snippet of code leads to a validation error, but it shouldn't (IMHO):

```ruby
p = Post.new
p.tags.build(:title => "Tag 1")
p.save! # Saves with no problem

p = Post.first
p.save! # Fails, complaining that tags cannot be blank
```

The same process works with no problem when using ActiveRecord, as AR issues a select statement fetching all the tags belonging to the post, before performing the validation. Mongoid should work in the same way IMHO.

Here's the ActiveRecord counterpart that works with no problem:

```ruby
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title

t.timestamps
end
end
end

class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :title
t.integer :post_id

t.timestamps
end
end
end

class Post < ActiveRecord::Base
has_many :tags
validates_presence_of :tags
end

class Tag < ActiveRecord::Base
belongs_to :post
end

p = Post.new
p.tags.build(:title => "Tag 1")
p.save!

p = Post.first
p.save!
```