Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-1676

validates_presence_of association should enable autosave

    • Type: Icon: Task Task
    • Resolution: Done
    • 3.0.0
    • Affects Version/s: None
    • Component/s: None
    • Labels:

      Having two models Post and Tag:

      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 :post
      end
      

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

      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
              # Even p.update_attributes!(:title => "New Title") Fails
      

      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:

      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!
      

            Assignee:
            Unassigned Unassigned
            Reporter:
            behrangsa behrangsa
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: