Mongoid从多个关联中获取模型

时间:2015-07-26 11:24:34

标签: ruby-on-rails ruby mongoid

我有UserShopFavouriteShop型号。我正在使用mongoid:

class User
   include Mongoid::Document
   has_many :favourite_shops, dependent: :destroy
end

class Shop
   include Mongoid::Document
   has_many :favourite_shops, dependent: :destroy
end

class FavouriteShop
   include Mongoid::Document
   include Mongoid::Timestamps

   belongs_to :user
   belongs_to :shop
end

正如您所看到的,通过UserShopFavouriteShop存在多对多关系。

现在如果我有一个用户:

user = User.all.first

如何获得与用户关联的所有商店?

1 个答案:

答案 0 :(得分:2)

使用user.favourite_shops.map(&:shop),您只需在每个用户的favourite_shops上调用#shop,然后接收一系列相关商店。换句话说,您将favourite_shops中的每一个替换为关联的shop

如果你想以Mongoid的方式做到这一点,请考虑这篇文章How to implement has_many :through relationships with Mongoid and mongodb?