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

relationships persisted even when record is invalid

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

      suppose I have two models like this:

      class Person
      include Mongoid::Document
      field :name
      validates_presence_of :name

      embeds_many :tags
      accepts_nested_attributes_for :tags
      end

      class Tag
      include Mongoid::Document
      embedded_in :person, :inverse_of => :tags
      end

      and i create a person with no tags

      gerad = Person.create :name => 'Gerad'

      finally, say my controller code tries to subsequently update the attributes for that person

      gerad.update_attributes(:tags_attributes => { '0' => { :name => 'tag' }}, :name => '')

      now, because of mongoid's automatic persistence of related documents if the parent record is persisted, I get an inconsistent state: namely the new tags have been persisted, but the name has not.

      gerad.reload
      gerad.name # => 'Gerad'
      gerad.tags.map(&:name) # => ['name']

      this is causing me problems in my controller code, because in the case of errors, I do not want the record partially saved, but I do want the associations preserved in memory so I can re-render the form correctly with the associations the user attempted to create

      as it stands, I can't figure out how to add embedded documents to the parent without persisting the parent, anybody have guidance?

            Assignee:
            durran Durran Jordan
            Reporter:
            gerad Gerad Suyderhoud
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: