【问题标题】:How do i access/select a specific embedded document in mongoid?如何在 mongoid 中访问/选择特定的嵌入文档?
【发布时间】:2013-03-23 01:23:52
【问题描述】:

有没有更好的方法来做到这一点?

class User
    embeds_many :groups

    def group(group_id)
        gid = Moped::BSON::ObjectId(group_id)
        self.groups.each.detect{|group| group.id == gid}
    end
end

class Group
    embedded_in :user
end

我正在以这种方式访问​​该组:

User.new.group(group_id)

如果用户有 1000 个嵌入组(假设),那么这是否意味着我必须遍历其中的 1000 个?有没有更好的方法来访问特定组?

【问题讨论】:

    标签: mongoid mongoid3


    【解决方案1】:

    您可以像普通模型一样查询Usergroups 属性。例如,如果您想通过其 id 查找特定的Group

    my_user.groups.find(group_id)
    

    也可以使用where查询:

    my_user.groups.where(id: group_id).first
    

    【讨论】:

      猜你喜欢
      • 2011-06-02
      • 1970-01-01
      • 2011-08-19
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      相关资源
      最近更新 更多