我在这个项目上使用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
拥有并属于Category
,BuilderType
,VoiceType
等等。目前,如果我想搜索属于特定类别的所有语音,请执行以下操作(伪代码):
@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)我怎么能这样做?
答案 0 :(得分:1)
这可能对您有用:
Voice.all(category_ids: [@cat1.id, @cat2.id]).
where(:voice_type_ids.in [@voice_type.id])
答案 1 :(得分:0)
为了将来的参考,最后我做的是:
@voices = Voice.all(category_ids: [@cat_1.id, @cat_2.id]).
and(voice_type_ids: @voice_type.id).map{ |voice| voice.format_frontend }