Christian Fazzini
Christian Fazzini

Reputation: 19723

Mongoid many-to-many, is this normal?

Here are my models:

class User
  include Mongoid::Document
  include Mongoid::Timestamps
  references_many :roles, :stored_as => :array, :inverse_of => :users
  ...
end

class Role
  include Mongoid::Document

  field :name, :type => String

  references_many :users, :stored_as => :array, :inverse_of => :roles
  ...
end

I first create the roles via seed, rake db:seed. My seed file contains:

puts '*** Add default roles'
[
  { :name  => 'User' },
  { :name  => 'Artist' }
].each do |h|
  Role.create(h)
end

The roles are created successfully. However, when I add a role to a user, I do:

foobar = User.first
foobar.roles.create(:name => 'User') 

I notice 2 things:

1) It adds the role as a reference in the User collection.

2) It creates a 3rd role in the Role collection.

This is kind of strange because now I have 3 roles: User, Artist and User. The 2nd User collection has a user_ids reference which contains foobar's id.

Is this normal?

Upvotes: 0

Views: 905

Answers (1)

pestaa
pestaa

Reputation: 4749

I think you rather want to do:

foobar = User.first
foobar.roles << Role.find(:name => 'User')
foobar.save

This way a role object is not created, but a reference is added to an already existing record.

Upvotes: 1

Related Questions