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

accepts_nested_attributes_for and lopsided has_and_belongs_to_many issue

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 5.0.1, 6.0.0, 5.1.1
    • Affects Version/s: None
    • Component/s: None
    • None

      I've run into an issue that I think I've tracked down to accepts_nested_attributes_for and a lopsided has_and_belongs_to_many.

      has_and_belongs_to_many :attendees, :class_name => 'Attendee', :inverse_of => nil
      accepts_nested_attributes_for :attendees, :allow_destroy => true

      It seems like this find query:

      def process_attributes(parent, attrs)
      return if reject?(parent, attrs)
      if id = attrs.extract_id
      first = existing.first
      converted = first ? convert_id(first.class, id) : id
      doc = existing.find(converted) # <============================================
      if destroyable?(attrs)
      destroy(parent, existing, doc)
      else
      update_document(doc, attrs)
      end
      else
      existing.push(Factory.build(metadata.klass, attrs)) unless destroyable?(attrs)
      end
      end

      https://github.com/mongoid/mongoid/blob/master/lib/mongoid/relations/builders/nested_attributes/many.rb#L102

      is translated into this:

      QUERY collection=attendees selector={"$and"=>[{"_id"=>{"$in"=>["5315f25c166093b274000001", "5315f25c166093b274000002"]}}], "_id"=>"5314ba811660930c03000002"}

      where the two other ids are for the two other models in the relation. The query will never match anything, since it basically where id == 1 && id == 2.

      A wild guess is that normally the query would be scoped based on the association, e.g. "parent_id" => {"$in"... but because of the lopsided HABTM-relation that does not happen and this query is run instead.

      I understand that this issue would be more complete with a test-case, but unfortunately I cannot provide that right now. Feel free to close this issue without action if you find it insufficient, but hopefully it's still somewhat useful (and perhaps someone else with a similar issue can chime in).

            Assignee:
            emily.stolfo Emily Stolfo
            Reporter:
            sandstrom sandstrom
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: