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

Sorting by relationships

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 12_01_17
    • Affects Version/s: None
    • Component/s: None
    • None

      So this is the predicament. I know the embeds_many allows you to embed documents into a parent document. This makes sorting by relations easier. However, I cannot have this, because my objects can be isolated entities. In other words, a contact cannot embed_many leads because a lead can exist independently of a contact.

      So the relationship I created is a has_one:

      class Contact
      include Mongoid::Document
      has_one :lead

      field :reference_number, type: String
      end

      class Lead
      include Mongoid::Document
      belongs_to :contact
      end

      It works fine, until I need to sort leads by contact reference number. Then I do not know how this can be done.

      In ActiveRecord, you can do this:

      Lead.joins(:contact).order('reference_number asc')
      Lead.joins(:contact).order('reference_number desc')

      But there is no way to sort by relations in Mongoid:

      contact_ids = Contact.order('reference_number asc').pluck :id
      Lead.in(contact_id: contact_ids)

      The above doesn't work. Any idea how to improve this problem?

            Assignee:
            Unassigned Unassigned
            Reporter:
            johnmerlino John Merlino
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: