Stussa
Stussa

Reputation: 3415

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

Upvotes: 9

Views: 504

Answers (4)

Mohamed Sami
Mohamed Sami

Reputation: 916

I think the best to follow this documentation Active Record Associations, I think defining another object_id will make you sustain the relation manually in your code and you will lose Active Record features for doing that.

Upvotes: 0

Marcelo Ribeiro
Marcelo Ribeiro

Reputation: 1738

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.

Upvotes: 2

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38012

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.

Upvotes: 3

Matouš Borák
Matouš Borák

Reputation: 15944

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.

Upvotes: 6

Related Questions