【问题标题】:Scopes with Rails and MongoRails 和 Mongo 的作用域
【发布时间】:2016-03-09 01:43:06
【问题描述】:

我有这 3 个具有 Mongoid 的依赖模型:

 class Account
   has_many :apps
 end

 class App
   belongs_to :account
   has_many :devices
 end

 class Device
   belongs_to :app
 end

我想获取属于一个帐户的所有设备元素,但是设备帐户之间的关系是通过模型应用程序。

ActiveRecord 环境中,它会是这样的:

scope :for_account, ->(account) { joins(:app).where("app.account = ?", account) }

我怎样才能用 Mongoid 做到这一点?

【问题讨论】:

  • 您认为最好的选择是什么?在 Device 类中包含“belongs_to :account”或引入类似“alize :app, :account_id”的内容?

标签: ruby-on-rails mongoid


【解决方案1】:

我能想到的两种方法来解决这个问题。

Mongoid 关系为我们提供了大量的方法来帮助我们访问对象。

例如:

app.account       #returns account object
app.account_id    #returns bson id of account object
account.apps      #returns collection of apps
account.app_ids   #returns array of app bson ids

我们可以使用它来查找应用 ID 包含在帐户的应用 ID 列表中的所有设备。比如:

Device.where(app_id: { '$in' => account.app_ids})

这将返回一个不错的集合,就像任何其他 mongo 查询一样,但有搜索整个 Device 集合的缺点。根据您的数据库大小,这可能是您不满意的性能损失。

或者:

account.apps.collect{ |a| a.devices}.flatten

将提供从一个帐户中的所有应用收集的设备项目的数组

这具有搜索效率更高的优势,并且该数组很可能适用于您需要此集合的任何内容。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    相关资源
    最近更新 更多