【问题标题】:How to convert mongoid criteria to array?如何将 mongoid 标准转换为数组?
【发布时间】:2019-10-31 07:23:42
【问题描述】:

我有一个 mongoid 标准 categories,我需要转换为数组。我正在使用categories.to_a,但这不起作用,并且总是通过.map 迭代mongoid 标准,它正在执行.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

【问题讨论】:

  • 您能否展示代码示例来说明您想要实现的目标? to_a 不起作用是什么意思?
  • 我提供了一些代码。你能帮忙吗?
  • to_a 不起作用是什么意思? :)
  • 我的意思是什么是实际行为和预期行为?
  • Mongoid 在迭代类别时总是做一个新的查询我只需要迭代一个数组而不是做更多的查询,因为我已经在.mapOffers中获得了报价的查询结果

标签: ruby-on-rails mongoid


【解决方案1】:

从标准开始:

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

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

bands = scope.to_a

...然后迭代数组任意次数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-23
    • 2019-04-20
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多