Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Polymorphic relation IDs are converted to strings with mongoid #1845

Open
glebtv opened this issue Nov 23, 2013 · 3 comments
Open

Polymorphic relation IDs are converted to strings with mongoid #1845

glebtv opened this issue Nov 23, 2013 · 3 comments

Comments

@glebtv
Copy link
Contributor

glebtv commented Nov 23, 2013

Mongoid won't fix it on their side: mongoid/mongoid#3386 saying it is 'by design', so I am reopening this here:

Currently, in mongoid polymorphic relation when setting id as string it is stored as string.
This doesn't break loading of relation (comment.commentable), but it breaks inverse relation (commenable.comments)

Rails Admin is setting polymorphic relations exactly this way, as strings, which breaks a lot of things in my apps after saving a model in rails_admin.

Currently, i am using a workaround like this:

before_validation do
  if commentable_id.class.name == 'String'
    self.commentable_id = BSON::ObjectId.from_string(commentable_id)
  end
  true
end

This is a pretty bad problem, because it causes comments to not be shown in app after any operation on them in rails admin.

Is there any easy way to properly fix this in rails admin without having to use workarounds like this?

@dabeto
Copy link

dabeto commented May 3, 2014

I wasted half a day figuring this out, I used your workarond. thanks!

@mattruzicka
Copy link

Another workaround would be to define field :commentable_id, type: BSON::ObjectId after the belongs_to :commentable, polymorphic: true.
That way you don't have to write a before_validation.

If you write it as
belongs_to :commentable, polymorphic: true; field :commentable_id, type: BSON::ObjectId
you can pretend it's an option to the polymorphic relation definition to enforce the type on the foreign key :)

I haven't had this code very long, so it's possible that there's a hidden issue with doing this. I'll come back to comment if I find one.

@TangMonk
Copy link

same issue.

thanks for @mattruzicka solution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants