【问题标题】:Create a Model Scope using hash attribute使用哈希属性创建模型范围
【发布时间】:2016-08-26 14:40:20
【问题描述】:

我在 Ruby 中使用 mongoid-history gem 和 mongoid。我实际上将 mongo 历史与名为 SocialPost 的模型相关联,所以我可以制作类似的东西。

history = current_user.social_posts.history_tracks

现在我需要使用从历史跟踪器模型中过滤属性“association_chain”的范围或方法过滤此“历史”,但“history_tracks”属性是以这种方式制作的:

<HistoryTracker _id: 57bdc1cb65e59325ae000001, created_at: 2016-08-24 15:48:27 UTC, updated_at: 2016-08-24 15:48:27 UTC, association_chain: [{"name"=>"SocialPost", "id"=>BSON::ObjectId('57ac8b0f65e5930944000000')}], modified: {"facebook_likes_count"=>2594213, "tweeter_followers_count"=>0}, original: {}, version: 1, action: "update", scope: "social_post", modifier_id: nil>

那么,我如何在我的 HistoryTracker 模型中创建一个搜索,允许我在 Association_chain 中搜索一组特定的 id,如下所示:

HistoryTracker.where(:association_chain.in => {"name"=>"SocialPost", "id"=>[GROUPS OF IDS TO SEARCH]}

使用 $elemMatch 更新

#test case multiple social_id: empty result
HistoryTracker.any_in({:association_chain.elem_match => [{name: 'SocialPost', :id.in => social_ids}] })

#test case 1 social_id: match result
HistoryTracker.any_in({:association_chain.elem_match => [{name: 'SocialPost', :id => social_ids.first}] })

【问题讨论】:

    标签: ruby model mongoid


    【解决方案1】:

    我已经找到了一个可行的解决方案。 elemMatch 应该与您需要收集的 id 分组构建,所以这就是我所做的:

    social_ids = [BSON::ObjectId('...1'), BSON::ObjectId('...2'), BSON::ObjectId('...3')]
    
    #reorder the ids with the extra hash elements
    a = []
    social_ids.each do |id_bson|
      a << {name: 'SocialPost', id: id_bson}
    end
    

    现在您创建 'QUERY'

    HistoryTracker.any_in({:association_chain.elem_match => a})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多