ruby on rails - Mongoid many-to-many, is this normal? -
here 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 roles via seed, rake db:seed. seed file contains:
puts '*** add default roles' [ { :name => 'user' }, { :name => 'artist' } ].each |h| role.create(h) end
the roles created successfully. however, when add role user, do:
foobar = user.first foobar.roles.create(:name => 'user')
i notice 2 things:
1) adds role reference in user collection.
2) creates 3rd role in role collection.
this kind of strange because have 3 roles: user, artist , user. 2nd user collection has user_ids reference contains foobar's id.
is normal?
i think rather want do:
foobar = user.first foobar.roles << role.find(:name => 'user') foobar.save
this way role object not created, reference added existing record.
Comments
Post a Comment