Suppose you have two models, User and City, joined by a third model CityPermission:
class CityPermission < ActiveRecord::Base belongs_to :city belongs_to :user end class City < ActiveRecord::Base has_many :city_permissions has_many :users, :through => :city_permissions end class User < ActiveRecord::Base has_many :city_permissions has_many :cities, :through => :city_permissions end
Currently, I create the join table, and the index for the table, using the following migration code snippet:
create_table :city_permissions do |t| t.integer :user_id, :city_id t.other_fields ... end add_index(:city_permissions, :user_id) add_index(:city_permissions, :city_id)
Are these the optimal indexes to create? Will these indexes allow quick access back and forth through the join table, as well as quick lookups within the table itself, or is there some other better way? To restate this a bit differently, will these indexes, given city and user are instance variables of class City and User, allow city.users, city.city_permissions, user.cities, and user.city_permissions to all perform equally well?
Looks good to me.
The joins generated should just be on either the PK IDs of the entity tables, or on the FK IDs in the join table – which are both indexes.
Probably would be good to look at the generated ActiveRecord SQL and compare it against the indexes.
Depending on what database you’re on you could then run that SQL through an Explain plan (or whatever tool exists, I’m thinking Oracle here)
To simplify your code, you could look at using
has_and_belongs_to_manyas well. That would let you get rid of the CityPermission object (unless you want to use that to store data in itself)