No idea why MongoMapper can't handle a Has And Belongs to Many Relationship No idea why MongoMapper can't handle a Has And Belongs to Many Relationship mongodb mongodb

No idea why MongoMapper can't handle a Has And Belongs to Many Relationship


Firstly, you'll need to specify that word_ids and topic_ids are array attributes in your models:

  class Topic    include MongoMapper::Document             many :words, :in => :word_ids    key :word_ids, Array    key :name, String  endclass Word  include MongoMapper::Document           many :topics, :in => :topic_ids  key :topic_ids, Array  key :word, Stringend

You'll also have to make sure that you are saving your topic and word in your rake task:

task :import => :environment do  File.open(Rails.root + 'lib/test.yml', 'r') do |file|    YAML::load(file).each do |topic, word_types|      puts "Adding #{topic}.."      temp_topic = Topic.create name: topic      temp_words = []      word_types.map do |type, words|        words.split(' ').map do |word|          word = Word.create type: type, word: word          word.topics << temp_topic          word.save          temp_words << word        end      end      temp_topic.words << temp_words.flatten      temp_topic.save    end  end  end

That gives me the following output:

{    "_id" : ObjectId("502bc54a3005c83a3a000006"),    "topic_ids" : [        ObjectId("502bc54a3005c83a3a000001")    ],    "word" : "groundation",    "type" : "reggae"}{    "_id" : ObjectId("502bc54a3005c83a3a000007"),    "topic_ids" : [        ObjectId("502bc54a3005c83a3a000001")    ],    "word" : "philip",    "type" : "classical"}  ....etc

and

{    "_id" : ObjectId("502bc54a3005c83a3a000001"),    "word_ids" : [        ObjectId("502bc54a3005c83a3a000002"),        ObjectId("502bc54a3005c83a3a000003"),        ObjectId("502bc54a3005c83a3a000004"),        ObjectId("502bc54a3005c83a3a000005"),        ObjectId("502bc54a3005c83a3a000006"),        ObjectId("502bc54a3005c83a3a000007"),        ObjectId("502bc54a3005c83a3a000008"),        ObjectId("502bc54a3005c83a3a000009")    ],    "name" : "Music I Dig"}