Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails polymorphic association without Type (unique id)

In my app, I have a unique id for each object (tables).

Now, because of that, when using seeing the id, I know what object type it is, whether it's a User or it's a Hotel.

I was wondering if I could save the lookup for the item_type in polymorphic associations, patch the lookup with an id sequence lookup in memory thus saving the space in the DB and in the index.

Can this be done?

I am working with Rails 3.0.9, Ruby 1.9.2

like image 732
KensoDev Avatar asked Dec 16 '11 13:12

KensoDev


1 Answers

This may not be the answer you're looking for. I'm sure this is possible somehow, but you'd be fighting against the grain of how polymorphism was designed in ActiveRecord, and that would probably cause a load of pain.

The first question that comes to me is why? You're asking for a performance optimization. Are you seeing a performance problem? Have you verified with instrumentation, New Relic, the Ruby profiler and other tools that this second lookup is really what is killing your performance? If you haven't done any of this, then you're probably wasting your time. Predicting performance bottlenecks is an inaccurate science and subject to the 80-20 rule.

If you really, really have this problem and you've been thorough in analyzing your logs, your New Relic charts, you've isolated the problem and run performance tests against it, if you've done all that, and you're seeing a performance problem right with this issue, then I'd suggest that probably a denormalization solution of sorts will give you some improvement. Denormalization is a common tool to optimize database performance problems. You'd be storing data in more than one place, but your queries will to touch fewer tables (faster), at the extra overhead of keeping the multiple bits in sync when updating records (more complex application code).

If you could post a bit more detail about your example, it would be easier to make some more concrete suggestions or give examples.

like image 165
Wolfram Arnold Avatar answered Dec 12 '22 13:12

Wolfram Arnold