【问题标题】:How to query for Mongoid documents by two references如何通过两个引用查询 Mongoid 文档
【发布时间】:2016-01-19 09:17:18
【问题描述】:

我在这个项目中使用 Mongoid。假设我有一个这样的模型:

class Voice

  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Enum
  include Mongoid::Paperclip

  enum :status, [:enabled, :disabled], :validate => true, :default => :enabled

  ...

  has_and_belongs_to_many                               :categories
  has_and_belongs_to_many                               :builder_types
  has_and_belongs_to_many                               :voice_types
  has_and_belongs_to_many                               :preferences
  has_and_belongs_to_many                               :languages
  embeds_many                                           :comments
  embeds_many                                           :ratings
  belongs_to                                            :artist,                        :class_name => "User"

  ...

end

如您所见,Voice 拥有并属于CategoryBuilderTypeVoiceType 等等。目前,如果我想搜索属于特定类别的所有声音,我会执行以下操作(伪代码):

@category = Category.find(id)
@voices = @category.voices

效果很好。如何搜索具有或属于多个关系和关系类型的Voice。例如(不工作的伪代码):

@cat1 = Category.find(id)
@cat2 = Category.find(id)
@voice_type = VoiceType.find(id)
@voices = @cat1.voices.where(category_id: @cat2.id).where(voice_type_id: @voice_type.id)

但这不起作用。如果 1) 完全有可能和 2) 我该怎么做?

【问题讨论】:

    标签: ruby-on-rails-4 mongoid


    【解决方案1】:

    这可能对你有用:

    Voice.all(category_ids: [@cat1.id, @cat2.id]).
      where(:voice_type_ids.in [@voice_type.id])
    

    【讨论】:

    • 很遗憾没有。它给了我一个错误:wrong number of arguments (1 for 0)
    【解决方案2】:

    为了将来参考,最后我所做的是:

    @voices = Voice.all(category_ids: [@cat_1.id, @cat_2.id]).
      and(voice_type_ids: @voice_type.id).map{ |voice| voice.format_frontend }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多