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

Validate belongs_to target when saving by default

    • Type: Icon: Improvement Improvement
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • None

      Mongoid by default requires that belongs_to association is populated in models. However, an invalid belongs_to target does not make a model invalid. There is an option to allow nil targets for belongs_to.

      ActiveRecord does not require belongs_to targets to be set. If this behavior is desired one can add a presence validator to the association.

      When assigning a non-persisted model as a belongs_to target, the source model is considered valid even if the target is not valid. However, assigning an invalid id to the belongs_to foreign key makes the source model invalid.

      With this, I believe the most sensible behavior for Mongoid is to at least require that belongs_to association targets are valid by default, if they are required to be present. It is probably easier and more consistent to always require association targets to be valid if they are present. (Note that AR's behavior of silently not saving targets can lead to data loss.)

      Remaining associations (has_one, specifically) should also be audited to see if this affects them.

            Assignee:
            neil.shweky@mongodb.com Neil Shweky (Inactive)
            Reporter:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: