How to avoid multiple, unused has_many associations when using multiple models for the same entity (

Posted by mikep on Stack Overflow See other posts from Stack Overflow or by mikep
Published on 2010-04-23T00:08:23Z Indexed on 2010/04/23 0:13 UTC
Read the original article Hit count: 293

Hello,

I'm looking for a nice, Ruby/Rails-esque solution for something.

I'm trying to split up some data using multiple tables, rather than just using one gigantic table. My reasoning is pretty much to try and avoid the performance drop that would come with having a big table. So, rather than have one table called books, I have multiple tables: books1, books2, books3, etc.

(I know that I could use a partition, but, for now, I've decided to go the 'multiple tables' route.)

Each user has their books placed into a specific table. The actual book table is chosen when the user is created, and all of their books go into the same table. The goal is to try and keep each table pretty much even -- but that's a different issue.

One thing I don't particularly want to have is a bunch of unused associations in the User class. Right now, it looks like I'd have to do the following:

class User < ActiveRecord::Base
  has_many :books1, :books2, :books3, :books4, :books5
end

class Books1 < ActiveRecord::Base
  belongs_to :user
end

class Books2 < ActiveRecord::Base
  belongs_to :user
end

First off, for each specific user, only one of the book tables would be usable/applicable, since all of a user's books are stored in the same table. So, only one of the associations would be in use at any time and any other has_many :bookX association that was loaded would be a waste.

I don't really know Ruby/Rails does internally with all of those has_many associations though, so maybe it's not so bad. But right now I'm thinking that it's really wasteful, and that there may just be a better, more efficient way of doing this.

Is there's some sort of special Ruby/Rails methodology that could be applied here to avoid having to have all of those has_many associations? Also, does anyone have any advice on how to abstract the fact that there's multiple book tables behind a single books model/class?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about model