brewster
brewster

Reputation: 4492

mongoid references_and_referenced_in_many

i have a strange problem. i am new to mongoid, so i am having trouble determining if it is me or mongoid at fault... presenting my code is perhaps the best explanation (minus the fields/validations/etc.)

class User
  include Mongoid::Document
  embeds_one  :profile, :class_name => "UserProfile"
  references_and_referenced_in_many :roles
end

class UserProfile
  include Mongoid::Document
  embedded_in :user
end

class Role
  include Mongoid::Document
  references_and_referenced_in_many :users
end

with the following associations, when i create instances of these objects like so...

user = User.new :username => 'username',
                :email => '[email protected]',
                :password => 'password'
user.build_profile  :first_name => 'John',
                    :last_name => 'Doe',
                    :birthday => Date.new(1980, 1, 1)
user.roles << Role.new(:name => 'Administrator')
user.save

...i can view this user with User.first or user

...i can view the profile with User.first.profile and user.profile

...i can view roles with user.roles but i CANNOT view them with User.first.roles.

another strange thing is user.roles.count AND User.first.roles.count both return 0, even though when i view user.roles, it returns [#<Role _id: 4d8c0173e1607cdeae00002c, name: "Administrator", user_ids: [BSON::ObjectId('4d8c0173e1607cdeae00002a')]>]. (User.first.roles returns an empty array)

this seems like a bug.

Upvotes: 1

Views: 1058

Answers (1)

zoras
zoras

Reputation: 953

use :autosave => true for the relational association

references_and_referenced_in_many :roles, :autosave => true

or you can explicitly save the role as

role = Role.new(:name => 'Administrator')
user.roles << role
role.save
user.save

This is due to changes in mongoid.2.0.0.rc.1 + listed here.

Relational associations no longer autosave when the parent relation is created. Previously a save on a new document which had a references_many or references_one association loaded would save the relations on it's first save. In order to get this functionality back, an :autosave => true option must be provided to the macro (This only applies to references_many and references_one)

Upvotes: 2

Related Questions