Skip to content

Instantly share code, notes, and snippets.

@DouweM
Created November 8, 2012 12:35
Show Gist options
  • Save DouweM/4038541 to your computer and use it in GitHub Desktop.
Save DouweM/4038541 to your computer and use it in GitHub Desktop.
#{rel}_ids= with Mongoid HABTM
% ./test.rb
a.b_ids = [b.id]
a.b_ids: ["509ba6a40b32cb7486000001"]
a.bs: []
b.a_ids: []
b.as: []
a.bs = [b]
a.b_ids: ["509ba6a40b32cb7486000001"]
a.bs: [#<B _id: 509ba6a40b32cb7486000001, _type: nil, a_ids: ["509ba6a40b32cb7486000002"]>]
b.a_ids: ["509ba6a40b32cb7486000002"]
b.as: []
#!/usr/bin/env ruby
require "rubygems"
require "mongoid"
Mongoid.configure do |config|
config.connect_to("mongoid_sandbox")
end
class A
include Mongoid::Document
has_and_belongs_to_many :bs, inverse_of: :as
end
class B
include Mongoid::Document
has_and_belongs_to_many :as, inverse_of: :bs
end
a = A.new
b = B.new
a.b_ids = [b.id]
puts "a.b_ids = [b.id]"
puts "a.b_ids: #{a.b_ids}"
puts "a.bs: #{a.bs.to_a}"
puts "b.a_ids: #{b.a_ids}"
puts "b.as: #{b.as.to_a}"
puts
a.bs = [b]
puts "a.bs = [b]"
puts "a.b_ids: #{a.b_ids}"
puts "a.bs: #{a.bs.to_a}"
puts "b.a_ids: #{b.a_ids}"
puts "b.as: #{b.as.to_a}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment