Skip to content

Instantly share code, notes, and snippets.

@ilpoldo
Created February 2, 2011 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilpoldo/808627 to your computer and use it in GitHub Desktop.
Save ilpoldo/808627 to your computer and use it in GitHub Desktop.
Trying to make sense of Mongoid's associations
require 'spec_helper'
class Instructor
include Mongoid::Document
embeds_many :courses
references_many :cool_rides
# references_many :trusted_collegues, :class_name => 'Instructor' #- raises NoMethodError 'entries' for #<Instructor:0x1062f1e10>
references_and_referenced_in_many :trusted_collegues, :class_name => 'Instructor'
end
class Course
include Mongoid::Document
embedded_in :instructor
# references_many :substitutes, :class_name => 'Instructor' #- raises NoMethodError 'first' for #<Course _id: 4d49eade8b8e6b955a000004, name: "First Aid">
references_and_referenced_in_many :substitutes, :class_name => 'Instructor'
end
class CoolRide
include Mongoid::Document
referenced_in :instructor
end
describe "mongoid" do
context "references_and_referenced_in_many seems to be the only way to" do
it "build on a references_may" do
mitch = Instructor.create(:name => 'Mitch Buchannon')
mitch.trusted_collegues.create(:name => 'Newmie')
mitch.trusted_collegues.should_not be_empty
end
it "build inside an embedded document" do
mitch = Instructor.create(:name => 'Mitch Buchannon')
first_aid = mitch.courses.create(:name => 'First Aid')
first_aid.substitutes.create(:name => 'C.J. Parker')
end
end
context "references_many" do
it "builds from the referenced" do
jetski = CoolRide.create(:type => 'Jet Ski', :color => '#DB3920')
mitch = Instructor.create(:name => 'Mitch Buchannon')
mitch.cool_rides << jetski
end
end
end
@ilpoldo
Copy link
Author

ilpoldo commented Feb 2, 2011

When I run the spec I get a rather unhelpful error message; my guess is there should be a symmetrical call in the Instructor document

.F

Failures:
  1) mongoid refernces_many builds on an embeds_many's references
     Failure/Error: first_aid.substitutes.create(:name => 'C.J. Parker')
     undefined method `first' for #<Course _id: 4d49e0a78b8e6b90a4000004, name: "First Aid">
     # ./mongoid_references_spec.rb:41

Finished in 0.01313 seconds
2 examples, 1 failure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment