views:

22

answers:

1

I am using Mongoid and have a project and a user model. in the Project model, I have a field

class Project
  include Mongoid::Document
  field :name
  field :user_ids, :type => Array
end

class User
  include Mongoid::Document
  field :email
end

I can find all the users belonging to one project, i.e., 'find this project's users'

@project  = Project.first # => 'Housework'
User.criteria.id(@project.user_ids) # => ['Bart','Lisa','Maggie']

But I am having a bit trouble finding all the projects belonging to one user, i.e, 'find this user's projects'

@user = User.first   # => 'Bart'
Project.where(:user_ids => @user.id) # doesn't work
Project.where(:user_ids.includes => @user.id) # not such method
Project.where(:user_ids => [@user.id]) # doesn't make sense to compare arrays, but tried anyway and doesn't work

I know that you can have another field in the User model to store project_ids, I would gladly do that, but I am just curious, is there a method to be used in finder conditions that works similarly to #includes? in ruby?

A: 

I found a solution to this. it is the all_in finder method

example:

Fruit.all[0].colors = ['red','green','blue'] #=> apple
Fruit.all[1].colors = ['yellow','green']     #=> banana

Fruit.all[2].colors = ['red', 'yellow']      #=> pineapple

To find all fruits that have the color red in their 'colors' array field, one can query:

Fruit.all_in(:colors => ['red'])

=>[apple, pineapple]

Nik