What are the implications of having a object_id / object_type on a model (for a polymorphic association) in regards to Object
itself containing an object_id
and that overriding it (http://ruby-doc.org/core-2.3.1/Object.html#method-i-object_id)?
class Event
belongs_to :object, polymorphic: true # object_id/object_type
end
When I search for object_id
through the whole codebase of one of my rails projects (including all gems), I can see over 200 hits. In Rails only, this is about 50 hits.
I'd expect problems with records comparison, using them as hash keys, putting them to set
s, perhaps also duplicating them with dup
. In Rails, record.object_id
is referenced in caching, has_many_through
associations, AREL, pretty printing the record, minitest expectations, also in pry debugger,
But just from quick-looking trough the code it is very hard to guess if it will cause problems or not and I generally tend to be very defensive about such potential problems - you'll never know for sure if your next usage of the object
will not break things in a way that is both very hard to debug and perhaps impossible to fix.
As I said above, I'd be very curious if you tried, but myself would rather name it belongs_to :thing, polymorphic: true
or better yet something even more specific.
If you attempt to define object_id
on a class you'll find that you get the following angry warning from the Ruby interpreter warning: redefining 'object_id' may cause serious problems
(try it from IRB). That sounds scary - and the incidents may be tied to specific versions of Ruby (and vary based on the version used). I'd recommend fixing this.
I believe you can belong_to object, while defining the foreign_key to something else, like foreign_key: :object_identifier. That way you dont have to worry about object_id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With