开发者

Embedded reference not saved

Under mongoid and rails 3 I have a collection of Users and a collection a Projects which embed many Relationships, the models are:

class User

include Mongoid::Document

field :name, :type => String

referenced_in :relationship, :inverse_of => :user

end

class Project

include Mongoid::Document

field :title, :type => String

embeds_many :relationships

end

class Relationship

include Mongoid::Document

field :type, :type => String

references_one :user

embedded_in :subject, :inverse_of => :relationships

end

My problem is that the referenced user of a relationship is never saved into the relationship. For example for following command only saves :type:

project1 = Project.new( :title => "project1", :relationships => [ {:type => "mast开发者_如何学Pythoner", :user => "4d779568bcd7ac0899000002"} ] )

My goal is to have a project document similar to this:

{ "_id" : ObjectId("4d77a8b2bcd7ac08da00000f"), "title" : "project1", "relationships" : [

{

"type" : "master",

"user" : ObjectId("4d775effbcd7ac05a8000002"),

"_id" : ObjectId("4d77a8b2bcd7ac08da000010")

}

] }

The :user is never present, am I missing something here? Thanks a lot for your help!

Ted


So a couple things you might want to change:

1) Avoid the field name "type" as this is a rails magic column name used by single table inheritance. Maybe change them to user_type and relationship_type.

2) With Mongoid 2.0 and up you can use Active Model syntax like has_many and belongs_to instead of references. http://mongoid.org/docs/relations/referenced/1-n.html

3) For your create, instead of assigning user with a user ID, try assigning a user object.

project1 = Project.new( :title => "project1", :relationships => [ {:type => "master", :user => User.first} ] )

Or you could assign a user_id like so:

project1 = Project.new( :title => "project1", :relationships => [ {:type => "master", :user_id => "the_use_id_you_want_to_associate"} ] )

FYI, you don't have to specify the inverse_of in "referenced_in :relationship, :inverse_of => :user". Just "referenced_in :relationship" will do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜