【问题标题】:Mongoid one-to-many relation query in Ruby on RailsRuby on Rails 中的 Mongoid 一对多关系查询
【发布时间】:2014-08-12 10:14:53
【问题描述】:

我在 Ruby on Rails 中使用 Mongoid,并使用以下定义创建了两个模型:

class Conversation
    include Mongoid::Document

    field :ctopic
    belongs_to :tag
end

class Tag
    include Mongoid::Document

    field :name, type: String
    has_many :conversations
end

我想要做的是获取所有具有指定标签的对话。例如,有一个名称为“已关闭”的标签,我想获取所有标签为“已关闭”的对话。

我尝试了以下两种方法,但都失败了:

方法一:

convs = Tag.where(name: component).Conversation.all()

原来是语法错误,无法编译成功

方法2:

my_tag = Tag.where(name: component)
convs = Conversation.where(tag: my_tag)

无法成功获取对话对象。

有没有人有可行的方法来实现我的目标?谢谢。

【问题讨论】:

    标签: ruby-on-rails mongoid mongodb-query


    【解决方案1】:

    您可以使用以下方法之一获取特定标签的所有对话

    # approach 1
    Tag.where(name: 'some_name').include(:conversations).each do |conversation|
      # you have the conversation here
    end
    
    # approach 2
    convs = Conversation.where(tag_id: "SOME_BSON_ID_OF_THE_TAG").to_a
    
    # approach 3
    my_tag = Tag.where(name: component).first
    my_tag.conversations
    
    # approach 4
    my_conv = Conversation.where(ctopic: 'some_value').first
    my_conv.tag.conversations
    

    你也可以参考Mongoid docs获取关于如何查询mongoid模型的完整参考

    【讨论】:

    • 谢谢。我发现方法 2 满足了我的需求,因为它允许多个集合连接查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多