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

Helpful error when forgetting the other side of an embed?

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

      I did this:

      class Response
      include Mongoid::Document
      embedded_in :resource
      field :value, type: String
      end

      class Resource
      include Mongoid::Document
      field :url, type: String

      1. embeds_many :responses
        end

      Note that I had the embeds_many commented out. A silly mistake, I know, but I just wanted to share the debugging process – in the hopes that maybe I can be enlightened – or hopefully, we can add a useful error message.

      In my app, resource.valid? caused a mysterious error:

      NoMethodError in ResponsesController#create

      undefined method `name' for nil:NilClass
      Rails.root: /Users/david/dev/sample-app

      Application Trace | Framework Trace | Full Trace
      mongoid (3.0.0.rc) lib/mongoid/validations/uniqueness.rb:245:in `validate_embedded'
      mongoid (3.0.0.rc) lib/mongoid/validations/uniqueness.rb:47:in `validate_each'
      activemodel (3.2.6) lib/active_model/validator.rb:153:in `block in validate'
      activemodel (3.2.6) lib/active_model/validator.rb:150:in `each'
      activemodel (3.2.6) lib/active_model/validator.rb:150:in `validate'
      activesupport (3.2.6) lib/active_support/callbacks.rb:310:in `_callback_before_17'
      activesupport (3.2.6) lib/active_support/callbacks.rb:418:in `_run*3393481399181526745*validate*1919942954378861761*callbacks'
      activesupport (3.2.6) lib/active_support/callbacks.rb:405:in `__run_callback'
      activesupport (3.2.6) lib/active_support/callbacks.rb:385:in `_run_validate_callbacks'
      activesupport (3.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'

      I took a look at line 245.

      def validate_embedded(document, attribute, value)
      return if skip_validation?(document)
      relation = document._parent.send(document.metadata.name)
      criteria = create_criteria(relation, document, attribute, value)
      add_error(document, attribute, value) if criteria.count > 1
      end

      So it turns out metadata was nil. But from there, I am left wondering what the problem might be.

      So, to make a long story short (too late) – I know that I just needed to uncomment the line above – is there an easy way on Mongoid's end to make a clear error message for something like this?

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

              Created:
              Updated:
              Resolved: