Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implications of Having an object_id Column in Rails

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
like image 880
Stussa Avatar asked Jun 03 '16 20:06

Stussa


3 Answers

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 sets, 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.

like image 60
Matouš Borák Avatar answered Nov 15 '22 03:11

Matouš Borák


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.

like image 3
Kevin Sylvestre Avatar answered Nov 15 '22 05:11

Kevin Sylvestre


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.

like image 2
Marcelo Ribeiro Avatar answered Nov 15 '22 03:11

Marcelo Ribeiro