views:

960

answers:

2

I have problem with mongomapper associations. I have one class names User and other named Model. User has many models but...

user = User.first
=> <User ...
user.models
=> []
Model.find_by_user_id(user.id.to_s)
=> <Model ...
Model.find_by_user_id(user.id.to_s).user == user
=> true

Class code (simplified):

class User
  include MongoMapper::Document

  # some keys definition

  many :models
end

class Model
  include MongoMapper::Document

  # some keys definitions

  belongs_to :user
end

What I am doing wrong?

A: 

What kind of errors or exceptions are you getting? The code you posted looks fine.

Jimmy Baker
I don't get any errors. Just user.models is empty array? I edited my question, in first version I missed this, sorry
Sebastian
+2  A: 

It appears that MM no longer uses String format for the FK column, so

Model.find_by_user_id(user.id.to_s)

should be

Model.find_by_user_id(user.id)

Furthermore, the datatype of the Model.user_id column should be set to

key :user_id, Mongo::ObjectID

When I ran into this problem, I had to delete and recreate my collection to get it to work- in other words I used to have user_id as a String, but it would only "take" when I switched it when I rebuilt my database. Luckily I am working with test data so that was easy enough.

Scott Miller