Monday, November 12, 2012

Optimizing Polymorphic Association Joins On STI Models

Optimizing Polymorphic Association Joins On STI Models: Lets' say you have a table of assigned_users.Users can be assigned to several different things, so you make it a polymorphic relationship:class User has_many :assigned_users, :as=>:userendclass AssignedUser belongs_to :user belongs_to :model, :polymorphic=>trueendclass Client has_many :assigned_users, :as=>:modelendclass Task < ActiveRecord::Base has_many :assigned_users, :as=>:modelend...and so on. At this point you'll have the following fields in your assigned_users table:iduser_idmodel_typemodel_idOK, so this assigned_users table is going to need some indexes. Like any sensible techie, you think about the most common access patterns, and create some indexes to optimize those:add_index :assigned_users, [:user_id]add_index :assigned_users, [:model_type, :model_id]Great, we're good to go. Things tick along nicely, your assigned_users table

DIGITAL JUICE

No comments:

Post a Comment

Thank's!