如何将蒙古式条件转换为数组?

时间:2019-10-31 07:23:42

标签: ruby-on-rails mongoid

我有一个蒙古式准则categories,我需要转换为数组。我使用的是categories.to_a,但是这种方法不起作用,并且总是会由于.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 个答案:

答案 0 :(得分:1)

从条件开始:

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

...从数据库中检索完整的结果集并存储在数组中:

bands = scope.to_a

...然后迭代数组多次:

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