作用域使用Rails和蒙戈

问题描述:

我有这样3个依赖模型与Mongoid作用域使用Rails和蒙戈

class Account 
    has_many :apps 
end 

class App 
    belongs_to :account 
    has_many :devices 
end 

class Device 
    belongs_to :app 
end 

我想获取belongs_to的账户的所有设备的元素,但设备之间的关系账号是通过型号App

ActiveRecord的环境,这将是这样的:

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

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

+0

你认为这是最好的选择?要在Device类中包含“belongs_to:account”或引入诸如“alize:app,:account_id”之类的内容? –

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

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包含在应用IDS的一个帐户列表中的所有设备。喜欢的东西:

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

这将返回一个很好的集合,就像任何其他蒙戈查询,但搜索整个设备采集的缺点。根据你的分贝大小,这可能是一个你不习惯的表现。

或者:

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

将提供的所有帐户中的所述应用程序的收集设备项的阵列

这具有更高效搜索的优势,并且很可能数组对于您需要的任何集合都可以正常工作。

希望这会有所帮助!