Skip to content

Instantly share code, notes, and snippets.

@saks
Created June 4, 2011 08:08
Show Gist options
  • Save saks/1007714 to your computer and use it in GitHub Desktop.
Save saks/1007714 to your computer and use it in GitHub Desktop.
strange N..N mongoid relation behavior
require 'mongoid'
Mongoid.configure do |config|
name = "gist_tests"
host = "localhost"
config.master = Mongo::Connection.new.db(name)
config.persist_in_safe_mode = false
end
class Book
include Mongoid::Document
has_and_belongs_to_many :authors, class_name: 'Author', inverse_of: 'books'
field :name
end
class Author
include Mongoid::Document
has_and_belongs_to_many :books, class_name: 'Book', inverse_of: 'authors'
field :name
end
Book.destroy_all
Author.destroy_all
Book.create name: 'foo', authors: [Author.create(name: 'bar'), Author.create(name: 'buz') ]
Book.first.update_attributes authors: [Author.where(name: 'bar').one]
p Book.first.authors.size
p Author.where(book_ids: Book.first.id).count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment