railsadminteam / rails_admin

RailsAdmin is a Rails engine that provides an easy-to-use interface for managing your data
MIT License
7.88k stars 2.25k forks source link

Polymorphic relation IDs are converted to strings with mongoid #1845

Open glebtv opened 10 years ago

glebtv commented 10 years ago

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 commented 10 years ago

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

mattruzicka commented 10 years ago

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 commented 9 years ago

same issue.

thanks for @mattruzicka solution!