Polymorphic associations with relations

159 views
Skip to first unread message

Paweł Kondzior

unread,
Feb 22, 2010, 4:20:34 PM2/22/10
to Mongoid
I started prototyping my application in Mongoid and i found bug in
polymorphism of related associations.

Example:

class Post
include Mongoid::Document
has_many_related :comments
end

class Comment
include Mongoid::Document
belongs_to_related :post, :inverse_of => :posts
end

This simple example oviosly will work
>> Post.create.comments.build
=> #<Comment _id: 4b82f3c4fab40bb78a00000c, post_id:
"4b82f3c4fab40bb78a00000b">

But when i will change belongs_to_related association name
into :postable

class Comment
include Mongoid::Document
belongs_to_related :postable, :inverse_of => :posts
end

Mongoid will lost association, so when i will try to build comments

>> Post.create.comments.build
=> #<Comment _id: 4b82f43bfab40bb7c6000003, postable_id: nil>

postable_id will be nil

I think I'm able to help resolving this issue but firstly i want to
know that this behaveiour is not intended.

Paweł Kondzior

unread,
Feb 23, 2010, 6:28:51 AM2/23/10
to Mongoid
I thnik prrevious code doesn't explain what i want to do with mongoid.
It explains what is not working.

I want to be able to create polymorphic association Comments for Post
and Gallery that will be separate relation (not part of post or
gallery) so Comment.count will return count of all comments in the DB

class Post
has_many_related :comments
end

class Gallery
has_many_related :comments
end

class Comment
belongs_to_related :commentable, :inverse_of => :comments
end

When i will try to build simple comment, it will lost it's commentable
association as i presented in before post.

Durran Jordan

unread,
Feb 23, 2010, 6:00:30 PM2/23/10
to mon...@googlegroups.com, Mongoid
I need to provide polymorphic behaviour on related associations. I'll
add a feature for that.

Sent from my iPhone

AccUser

unread,
Mar 17, 2010, 12:20:53 PM3/17/10
to Mongoid
I've just hit the same issue:

class Group
include Mongoid::Document

has_many_related :pages, :as => :container
end

class Page
include Mongoid::Document

field :body

belongs_to_related :container, :polymorphic => true
end

Assuming I have a valid @group, that I want to be able to do the
following:

@group.pages.create(:body => 'This is a test')

Currently, I get an error:

NoMethodError: undefined method 'group_id=' for #<Page:0x105215038>

Presumably because :polymorphic option is not currently supported.

On Feb 23, 11:00 pm, Durran Jordan <dur...@gmail.com> wrote:
> I need to provide polymorphic behaviour on related associations. I'll
> add a feature for that.
>
> Sent from my iPhone
>

Reply all
Reply to author
Forward
0 new messages