Skip to content

Instantly share code, notes, and snippets.

@mrsimo
Created October 22, 2011 21:50
Show Gist options
  • Save mrsimo/1306527 to your computer and use it in GitHub Desktop.
Save mrsimo/1306527 to your computer and use it in GitHub Desktop.
# In ActiveRecord I'd usually do when I want to find the organization but only if the user belongs to it:
current_user.organizations.find(params[:id])
# With a has_and_belongs_to_many relationship with Mongoid, I have to do this:
Organization.where(:_id => params[:id], :user_ids => current_user.id).first
# => #<Organization _id: 4ea3302c2907207f5100000f ...
# Because:
current_user.organizations
# => [#<Organization _id: 4ea3302c2907207f5100000f ...>]
current_user.organizations.find(params[:id])
# => Mongoid::Errors::DocumentNotFound
current_user.organizations.where(:_id => params[:id]).first
# => nil
current_user.organizations.where(:id => params[:id]).first
# => nil
current_user.organizations.all(:_id => [params[:id]]).first
# => #<Organization _id: 4ea3302c2907207f5100000f...>
# I believe the nicest is the last one, once you understand how mongoid does the queries. Because it's a habtm
# relation, there's an organization_ids in the user, so it does a query for Organizations with an 'in' clause
# using all the organization_ids. Later on you can add another clause to get only the one you want.
current_user.organizations.all(:_id => [params[:id]])
# => #<Mongoid::Criteria
# selector: {:_id=>{"$in"=>[BSON::ObjectId('4ea3302c2907207f5100000f')], "$all"=>[BSON::ObjectId('4ea3302c2907207f5100000f')]}},
# options: {},
# class: Organization,
# embedded: false>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment