Как преобразовать критерии mongoid в массив? - PullRequest
0 голосов
/ 31 октября 2019

У меня есть критерий mongoid categories, и мне нужно преобразовать в массив. Я использую categories.to_a, но это не работает, и всегда критерий mongoid повторяется на .map, он выполняет .find новый запрос.

Как я могу это исправить?

def self.mapOffers (array, user)
    array.map { |u|

      {
      :id             => u.id.to_s,
      :name           => u.name,
      :description    => u.description,
      :price          => u.price,
      :url            => u.url,
      :categories     => Category.mapCategories(u.categories.to_a, user),
      :picture        => u.picture.url,
      :accepts_cash   => u.accepts_cash_transactions,
      :location       => {
        :longitude      => u.longitude,
        :latitude       => u.latitude,
        :street         => u.street,
        :neighborhood   => u.neighborhood,
        :number         => u.number,
        :zip            => u.zip,
        :city           => u.city,
        :state          => u.state,
        :complement     => u.complement,
        :country        => u.country,
      },
      :fixedMeetingPoint => u.fixedMeetingPoint,
      :meetingPoint   => {
        :street       => u.meetingPointStreet,
        :neighborhood => u.meetingPointNeighborhood,
        :number       => u.meetingPointNumber,
        :zip          => u.meetingPointZip,
        :city         => u.meetingPointCity,
        :state        => u.meetingPointState,
        :complement   => u.meetingPointComplement,
        :country      => u.meetingPointCountry,
        :latitude     => u.meetingPointLatitude,
        :longitude    => u.meetingPointLongitude,
      },
      :notes  => u.notes,
     }}
  end
def self.mapCategories (array, user)
    array.map { |u| {
     :id => u.id.to_s,
     :name => u.name,
     :selected => !user.nil? && u.users.include?(user),
     :picture => u.picture.url,
     }}
  end

1 Ответ

1 голос
/ 31 октября 2019

Начиная с критериев:

scope = Band.where(name: 'foo')

... получить полный набор результатов из базы данных и сохранить в массиве:

bands = scope.to_a

... затем выполнить итерацию любого массиваколичество раз:

bands.each { |band| ... }
bands.each { |band| ... }
...