views:

436

answers:

3

When I define the User has_many meetings, it automatically creates a "user_id" key/value pair to relate to the User collections. Except I can't run any mongo_mapper finds using this value, without it returning nil or [].

Meeting.first(:user_id => "1234")

Meeting.all(:user_id => "1234")

Meeting.find(:user_id => "1234")

All return nil. Is there another syntax? Basically I can't run a query on the automatically generated associative ObjectId.



# Methods

class User
  include MongoMapper::Document

  key :user_name, String, :required => true
  key :password, String

  many :meetings
end

class Meeting
  include MongoMapper::Document

  key :name, String, :required => true
  key :count, Integer, :default => 1
end


# Sinatra

get '/add' do
  user = User.new
  user.meetings  "foobar") #should read: Meeting.new(:name => "foobar")
  user.save
end

get '/find' do
  test = Meeting.first(:user_id => "4b4f9d6d348f82370b000001") #this is the _id of the newly create user
  p test # WTF! returns []
end
A: 

You can try using

Meeting.find_by_user_id "1234"

Also, if you run script/console then does Meeting.all show each record as having a user_id assigned to it?

Jimmy Baker
A: 

What about just User.find("1234").meetings ?

Ckhrysze
+1  A: 

As Jimmy mentioned about checking Meeting.all, I don't think you would have anything.

Based on your example above I see a couple potential issues.
- Your User requires a :user_name so it's not getting saved
- would never get saved, because you didn't set the name which is required
- Your Meeting isn't getting saved either
- One more thing, you need to concat your meeting to user.meetings

This works with mongo_mapper 0.6.10

require 'rubygems'
require 'mongo_mapper'
MongoMapper.database = "meetings"

class User
  include MongoMapper::Document

  key :user_name, String, :required => true
  key :password, String

  many :meetings
end

class Meeting
  include MongoMapper::Document

  key :name, String, :required => true
  key :count, Integer, :default => 1
end

user = User.create(:user_name => "Rubyist")
user.meetings  << Meeting.create(:name => "foobar")
user.save

Meeting.first(:user_id => user.id)
User.find(user.id).meetings

You may have figured this out already, but I hope this is helpful anyway.

ToreyHeinz