However, if you'll ever want to access the fans separately, I'd say
just do the reference instead. In either event, you don't need both.
Nicholas
If you use embeds_many :fans and store and access the Fans like so:
u = User.first
u.fans << Fan.new(params)
u.save
When you query for:
u = User.first
u.fans # => this will return all of the User's fans.
No need to explicitly store the user's ID.
I'm still puzzled why you want a reference as well... Are you looking
to query the Fans using different syntax than I outlined above?
Nicholas
Using this syntax, you're assuming that the Fans are stored in a
separate collection (and is referenced in the User model), and thus,
can call create!.
However, if you choose to use embedded documents, you'll need to use
the syntax outlined in my previous email.
> foo = User.first
> foo.name
> foo.fans.first.user.name
That third line isn't going to look like that. I think your concept of
embedded documents is a bit fuzzy. Take a look here:
http://mongoid.org/docs/associations/ and
http://www.mongodb.org/display/DOCS/Schema+Design
Now, like Brandon said - here's what you'll need to do:
class User
include Mongoid::Document
field :name # add , :type => String, or whatever if you want
embeds_many :fans
end
class Fan
include Mongoid::Document
embedded_in :user, :inverse_of => :fans
field :city # or whatever fields you want to add
end
We can create a
Now, we can query with:
fan = User.first.fans.first # We're getting the first user, and
returning the first item from the embedded array of fan documents
and we can call:
fan.city # This is the address we gave to the fan document
We add new fans like so:
u = User.first
u.fans << Fan.new(:city => "Buffalo")
u.save
Note: this may seem crazy, to those who are used to relational
databases. Because we've embedded the Fan into the user document, we
have to pull the user first, then return that user's fans. MongoDB
does all of the scoping that might be required in MySQL automatically.
Hopefully, this helps.
Nicholas
Nicholas
It really sounds like you need to immerse yourself in the MongoDB way
of thinking, (i.e. read the documentation I sent) then try again to
execute this.
You are actually going to want to use the references_and_referenced_in_many macro that will be included in the rc coming out soon. You will need to do it twice, once for each direction of fanning.
--Paul
Sorry it's been so quiet. It still isn't quite ready to be rebased into master. I'll share any information when I have some.
--Paul
please take a closer look at my example
https://github.com/saLOUt/rails_tutorial/blob/mongoid/app/models/user.rb
.
> following << user
will modify user.followers as well. You don't need your second part.
I tested the above mentioned class in rails console and it works for me.
Maybe you want to take my class as a starting point.
Best regards,
Robert