【问题标题】:Mongomapper query on the keys of a hash对哈希键的 Mongomapper 查询
【发布时间】:2011-08-16 22:44:02
【问题描述】:

我有一个一天的模型,每一天都包含一个标签哈希。

class Day
  include MongoMapper::Document

  key :tags, Hash
  ...
end

标签哈希可能看起来像这样 {"a"=>4, "b"=>1, "c"=>1}

我想写一个查询,可以找到标签键等于'a'的所有日子。

Day.where('tags.keys' => "a")

这不起作用,因为键实际上不是哈希中的键,我猜我不能只使用键方法。

我真的很想知道是否有办法查询散列的键,否则我将不得不创建一个数组来存储键并进行查询。

tags = {"a"=>4, "b"=>1, "c"=>1, "names" => ["a", "b", "c"]}

Day.where('tags.names' => "a") #This would work find, but is not what I want

【问题讨论】:

    标签: ruby-on-rails-3 hash key mongomapper


    【解决方案1】:

    我找到了解决办法。

    Day.where('tags.a' => {'$exists' => true})

    这将返回带有“a”键的所有日期。

    其实我可以像这样为Day写一个方法

    def self.find_all_by_tag(tag)
      Day.where("tags.#{tag}" => {'$exists' => true}).all
    end
    

    那么很容易通过这样的某个标签来获取所有天数:

    Day.find_all_by_tag("a")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2013-02-24
      相关资源
      最近更新 更多