如何使用 MongoDB 和 Rails 查询嵌套属性

How to query nested attributed with MongoDB and Rails

在下一个代码行中不起作用

filter[:category_fields][:name] = params[:filter_category]

不参与查询,只有第二个过滤器起作用:

if params[:commit] == 'Filter' && (params[:filter_category] != '' || params[:filter_status] != '')
  if !params[:filter_category].blank?
    filter[:category_fields][:name] = params[:filter_category]
  end
  if !params[:filter_status].blank?
    filter[:status] = params[:filter_status]
  end
  @articles = Article.where(filter).order('created_at DESC')  
else
  @articles = Article.all.reverse
end

也许我不应该在一个 "filter" 哈希中添加所有参数?

我的 Mongodb 看起来像:

{
    "_id" : ObjectId("57d115b3bf5918085c455ac3"),
    "views" : 0,
    "status" : "published",
    "title" : "sdfSDffd",
    "description" : "gsdfg",
    "content" : "sdfg",
    "category_id" : ObjectId("57d16aeebf59181133d3c35d"),
    "updated_at" : ISODate("2016-09-08T14:28:34.257Z"),
    "created_at" : ISODate("2016-09-08T07:39:31.757Z"),
    "category_fields" : {
            "name" : "sdfg"
    },
    "published_on" : ISODate("2016-09-08T11:56:48.407Z")
}

谢谢!

奇怪,但是用另一种形式写的散列赋值有帮助:

filter.store(:category_fields, {:name => params[:filter_category]})

最后我的索引看起来像:

def index
  filter = Hash.new
  if params[:commit] == 'Filter' && (params[:filter_category] != '' || params[:filter_status] != '')
    if !params[:filter_category].blank?
      filter.store(:category_fields, {:name => Category.find(params[:filter_category]).name})
    end
    if !params[:filter_status].blank?
      filter.store(:status, params[:filter_status])
    end
    @articles = Article.where(filter).order('created_at DESC')
  else
    @articles = Article.all.reverse
  end
end