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

Relationship in as_json method returning parent attributes key values

    • Type: Icon: Task Task
    • Resolution: Cannot Reproduce
    • Priority: Icon: Major - P3 Major - P3
    • 5.0.2
    • Affects Version/s: None
    • Component/s: None
    • None

      I have Two model, Unit & Resident and following relationship.

      class Unit 
        belongs_to :primary_resident, class_name: "Resident", inverse_of: :primary_in_units
      end
      
      class Resident
        has_many :primary_in_units, class_name: "Unit", inverse_of: :primary_resident, dependent: :nullify
      end
      

      When I am firing this command on rails console.
      Unit.last.as_json(only: [:uuid, :name ], methods: :primary_resident)

      Primary resident return only uuid and name that is keys specified for unit model.

      After debugging, I found that mongoid serialize calling relation with all options we have passed which they should not.

        File: lib/mongoid/serializable.rb
      
         def serialize_attribute(attrs, name, names, options)   
            if relations.has_key?(name)
              value = send(name)
              attrs[name] = value ? value.serializable_hash(options) : nil 
            elsif names.include?(name) && !fields.has_key?(name)
              attrs[name] = read_attribute(name)
            elsif !attribute_missing?(name)
              attrs[name] = send(name)
            end 
         end
      

      Here name is relationship in our case it is primary_resident , then it is passing same options to even relationship objects.

      I know the correct way to do this is to use include: but using the above methods: option should definitely throw an error and does not return me primary_unit with same keys as specified for unit model?

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

              Created:
              Updated:
              Resolved: