Hutch
Hutch

Reputation: 841

MongoID query for a collection that references a collection that references a collection

I have a User model, a Workout model and a Exercise model. I am using Devise for user management and MongoID to interact with MongoDB.

User references_many :workouts
Workout references_many :exercises and referenced_in :user
Exercise referenced_in: workout

How do I query the database to give me a list of all the current_user exercises.I have not stored the user.id in the exercise collection, only the workout.id.

Is it possible, or should I rework the model to store the user_id in both the exercise and workout collections?

Thanks

Upvotes: 1

Views: 543

Answers (1)

jared
jared

Reputation: 1647

How about something like this:

workout_ids = Workout.where(:user_id => current_user.id ).all.collect { |w| w.id }

exercises = Exercise.where(:workout_id => { "$in" => workout_ids })

Upvotes: 2

Related Questions