Mongoid聚合结果成为Rails模型的实例

问题描述 投票:0回答:1

简介

更正遗留代码,有一个对象LandingPage的索引,其中大多数列应该是可排序的,但不是。大多数情况已得到纠正,但很少有专栏继续给我带来麻烦。

这些列是需要汇总的列,因为基于其他文档的数量。为了简化对问题的解释,我只讲其中一个称为Visit,因为其余的代码将只是重复的。

代码获取排序并分页的数据,然后在返回json之前使用LandingPage方法修改每个对象。就像这样,我无法修改。

因此,我需要进行汇总(以LandingPage计数对Visit进行排序),然后将该对象作为LandingPage实例,以使旧代码可以在其上工作。

问题是无法将Mongoid :: Document转换为LandingPage实例

这是我得到的错误:

Mongoid::Errors::UnknownAttribute:
Message:
  unknown_attribute : message
Summary:
  unknown_attribute : summary
Resolution:
  unknown_attribute : resolution

这是我的代码:

def controller_function
    landing_pages = fetch_landing_page 
    landing_page_hash[:data] = landing_pages.map do |landing_page|
        landing_page.do_something
        # Do other things
    end
    render json: landing_page_hash
end

def fetch_landing_page
    criteria = LandingPage.where(archived: false)

    columns_name = params[:columns_name]
    column_direction = params[:column_direction]

    case order_column_name
    when 'visit'
      order_by_visits(criteria, column_direction)
    else
      criteria.order_by(columns_name => column_direction).paginate(
                   per_page: params[:length],
                   page: (params[:start].to_i / params[:length].to_i) + 1
                 )
    end

    def order_by_visit(criteria, order_direction)


  def order_by_visits(landing_pages, column_direction)
      LandingPage.collection.aggregate([
          { '$match': landing_pages.selector },
          { '$lookup': {
              from: 'visits',
              localField: '_id',
              foreignField: 'landing_page_id',
              as: 'visits'
          }},
          { '$addFields': {  'visits_count': { '$size': '$visits' }}},
          { '$sort': { 'visits_count': column_direction == 'asc' ? 1 : -1 }},
          { '$unset': ['visits', 'visits_count'] },
          { '$skip': params[:start].to_i },
          { '$limit': params[:length].to_i }
      ]).map { |attrs| LandingPage.new(attrs) { |o| o.new_record = false } }
  end
end

我尝试过的

  • 将控制台中的哈希复制并粘贴到LandingPage.new(attributes),并且实例已创建且有效。
  • [将属性键从字符串更改为符号,但仍然无效。
  • 在返回数组的任何元素上使用is_a?(hash)将返回true。
  • 将其放入json,然后返回到哈希。仍然有一个Mongoid :: Document。

如何使Aggregate的返回成为LandingPage的有效实例?

ruby-on-rails ruby mongodb mongoid
1个回答
0
投票

聚合管道是由Ruby MongoDB驱动程序而不是Mongoid实现的,因此不会返回Mongoid模型实例。

documentation中提供了一个如何获取Mongoid模型实例的示例。

© www.soinside.com 2019 - 2024. All rights reserved.