2

I have User, Shop and FavouriteShop models. I'm using 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

As you can see, there is many-to-many relationship with User and Shop via FavouriteShop.

Now If I got one user:

user = User.all.first

How can I get all Shops which are associatied to User?

Mr.D
  • 7,353
  • 13
  • 60
  • 119

1 Answers1

2

By using user.favourite_shops.map(&:shop) you simply call the #shop on each of the user's favourite_shops and receiver an array of related shops. In other word, you replace each of the favourite_shops with the associated shop.

If you wanted to do that a Mongoid way , please consider this post How to implement has_many :through relationships with Mongoid and mongodb?.

Community
  • 1
  • 1
adamliesko
  • 1,887
  • 1
  • 14
  • 21
  • You mentioned that it is not best relation in mongoid. why? I think there will be additional information in `FavouriteShop` model. – Mr.D Jul 26 '15 at 12:43
  • If you are going to add more data to the `FavouriteShop` then it is finde andsuitable :). But if used only as a M:N resolution entity, I would trash it:). – adamliesko Jul 26 '15 at 12:52