Mongoid foreign key in embedded document

Go To StackoverFlow.com

0

Let's say I have two models: board, that belongs to an user, and sharing which is embedded into board

board.rb

belongs_to :user
embeds_one :sharing

is possible to set the foreign key "user_id" in a field in sharing, something like:

belongs_to :user, :foreign_key => 'sharing.user_id'
2012-04-03 19:58
by Matteo Pagliazzi


0

Yes, just add user_id as a field on your embedded Sharing model.

2012-04-03 21:36
by Tyler Brock
And how to reference it as a foreign key? sharing.userid or sharing[:userid - Matteo Pagliazzi 2012-04-04 09:05
In general, if its a dynamic field it can't be referenced via the . so you have to use the [] notation. However for embedded documents you should be all right using the dot notation - Tyler Brock 2012-04-06 16:31
please don't answer if you're not sure, this doesn't work - Matteo Pagliazzi 2012-04-11 16:31
I'm positive it works, I've done it before. Please read the documentation. http://mongoid.org/docs/documents/dynamic.htm - Tyler Brock 2012-04-11 19:23
Tried with sharing.shared_with (shared with is definet not dynamic) and it says it doesn't accept dots... Tried using the array syntax it work - Matteo Pagliazzi 2012-04-11 21:11
Ads