Skip to content

Instantly share code, notes, and snippets.

@rapind
Created June 14, 2011 16:47
Show Gist options
  • Save rapind/1025311 to your computer and use it in GitHub Desktop.
Save rapind/1025311 to your computer and use it in GitHub Desktop.
Mongoid HABTM Issue
class Left
include Mongoid::Document
field :title, :type => String
has_and_belongs_to_many :rights
end
require 'rubygems'
require 'mongoid'
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("habtm_test")
end
puts 'Empty our database.'
Mongoid.master.collections.reject { |c| c.name =~ /^system/}.each(&:drop)
require 'left'
require 'right'
puts 'Create a left and a right object.'
left = Left.create!(:title => 'Left Test')
right = Right.create!(:title => 'Right Test')
puts "Find first left: #{Left.first.inspect}"
puts "Find first right: #{Right.first.inspect}"
puts 'Associated them to each other.'
left.rights << right
puts "Rights associated with lefts: #{left.rights.inspect}"
puts "Lefts associated with rights: #{right.lefts.inspect}"
puts 'Clear the association collection.'
left.rights.clear
puts "Rights associated with lefts: #{left.rights.inspect}"
puts "Lefts associated with rights: #{right.lefts.inspect}"
puts 'Retrieve the first left and first right object from the database.'
puts "Find first left: #{Left.first.inspect}"
puts "Find first right: #{Right.first.inspect}" # We no longer have our right object!
puts '** Notice that "Right.first.inspect" returns nil. It was deleted when we cleared the habtm collection.\n\n'
puts "Let's associate them again, but this time set the collection to [] instead of using clear."
puts "Create a new right object."
right = Right.create!(:title => 'Right Test')
puts 'Associated them to each other.'
left.rights << right
puts "Rights associated with lefts: #{left.rights.inspect}"
puts "Lefts associated with rights: #{right.lefts.inspect}"
puts 'Set the collection to an empty array [].'
left.rights = []
puts "Rights associated with lefts: #{left.rights.inspect}"
puts "Lefts associated with rights: #{right.lefts.inspect}"
puts 'Retrieve the first left and first right object from the database.'
puts "Find first left: #{Left.first.inspect}"
puts "Find first right: #{Right.first.inspect}" # We no longer have our right object!
puts '** Notice that this time the right object was NOT deleted, but the associations were properly cleared using the = syntax.'
class Right
include Mongoid::Document
field :title, :type => String
has_and_belongs_to_many :lefts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment