Ruby on Rails Friday, September 30, 2011

Rob Biedenharn wrote in post #1024309:
> You should not need an `id` on the admins table, but you almost
> certainly want to have an index on each of the `file_id` and `user_id`
> columns.

I assume you meant an unique index across both file_id and user_id. In
essence using the two foreign keys as the primary key of the join table.
It would not be sufficient to prevent duplicate records in the join
table with separate indexes on each foreign key.

file_id (PK1, FK1)
user_id (PK2, FK2)

However, IMO it is still best to let ActiveRecord have its unique
surrogate primary key. But, that does not preclude the need for a unique
index spanning the two foreign key columns.

Which ends up looking something like this:

add_index(:admin, [:file_id, :user_id], :unique => true)

In many cases it also does matter which column is listed first in the
index. Try to guess which of the two keys will be the most "selective"
once the database is filled with data. Will users tend to have a lot of
files associated them them, or will files have lots of users? That
depends on how your tables are actually going to be used. List first the
column that will tend to produce the fewest number of rows in the
result, for the majority of your queries.

Here are two examples that I think illustrate join tables well:

This first example is the typical style of join tables used by Rails.
There is actually a good reason for this. In an Object Relational
Mapping (ORM) environment it's really not a bad idea to let the model
classes maintain record identity. That allows ActiveRecord to use its
own built-in mechanism for mapping object instances to database rows.

Note: In order to conform to AR default naming replace relation_id with
id.

CREATE TABLE posts_tags (
relation_id int UNSIGNED NOT NULL AUTO_INCREMENT,
post_id int UNSIGNED NOT NULL,
tag_id int UNSIGNED NOT NULL,
PRIMARY KEY(relation_id),
UNIQUE INDEX(post_id, tag_id)
);

Here is a more traditional table definition. This is what I choose when
not working within an ORM environment (rarely these days):

CREATE TABLE posts_tags (
post_id int UNSIGNED NOT NULL,
tag_id int UNSIGNED NOT NULL,
PRIMARY KEY(post_id, tag_id)
);

These examples were take from:
http://20bits.com/articles/10-tips-for-optimizing-mysql-queries-that-dont-suck/

--
Posted via http://www.ruby-forum.com/.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment