我有User
,Shop
和FavouriteShop
型号。我正在使用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
正如您所看到的,通过User
与Shop
和FavouriteShop
存在多对多关系。
现在如果我有一个用户:
user = User.all.first
如何获得与用户关联的所有商店?
答案 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?。