amy-bo-bamy
amy-bo-bamy

Reputation: 45

Creating embedded documents, doesn't seem to create relationship

I have the following models defined in Rails, with Mongoid:

Class Character
  include Mongoid::Document
  field :n, as: name, type: String
  field :p, as: :positions, type: Array
  field :o, as: :roles, type: Array 
  field :r, as: :resource, type: String
  embeds_one :base_stat
end

class BaseStat
  include Mongoid::Document
  embedded_in :character
end

I'm trying to seed my database with documents that have these relationships 1) because I'd have to eventually and 2) so I can test I'm using Mongoid correctly. I've tried a couple of different ways to seed it, but every single time, I can create Character documents, then create BaseStat documents based off a Character document, but calling character.base_stat returns nil.

Here are the things I've tried in db/seeds.rb that didn't throw errors:

ch = Character.create!([etc])
ch.build_base_stat([etc])

Character.create!(name: value, name: value, base_stat: BaseStat.new(name: value, name:value))

ch = Character.create!([etc])
ch.create_base_stat([etc])

I've also tried using ch.base_stat.create! (which threw an error when I called rake db:setup).

I know that both the Character and BaseStat documents are created because I can search in the Rails console for the Character documents that were seeded (a = Character.where(name: value)[0] and b = BaseStat.where(name:value)[0]). But it looks like the relationship isn't being stored.

Calling a.metadata also throws a NoMethodError.

I don't have any controllers set up, just the models and the entries in db/seeds.rb. I feel like I must be missing something fundamental because, well, I've been hunting through StackOverflow and haven't seen anything that fixed this.

Versions: Mongoid 4.0.0.alpha2 Rails 4.0.1

Upvotes: 1

Views: 296

Answers (2)

Ahmad Sherif
Ahmad Sherif

Reputation: 6223

Quoting Mongoid docs, this could be why:

One core difference between Mongoid and Active Record from a behavior standpoint is that Mongoid does not automatically save child relations for relational associations. This is for performance reasons.

Try adding autosave: true to your base_stat relation:

embeds_one :base_stat, autosave: true

Upvotes: 0

Mike S
Mike S

Reputation: 11429

Have you tried a very basic test? Can you open the rails console create a Character, save it, then add a BaseStat to it and save that?

c = Character.new
b = BaseStat.new
b.name = "test"
c.base_stat = b
c.save
c

Does that print out your new record with the BaseStat embedded? If it does then there must be something wrong with the syntax or method in the seeds.

Upvotes: 2

Related Questions