2

A has_many polymorphic association usually gets indexed like the following:

# The migration:
t.references :commentable, polymorphic: true, index: true

# Produces this in the schema:
add_index "comments", ["commentable_id", "commentable_type"], name: "index_comments_on_commentable_id_and_commentable_type"

However, I have a has_one polymorphic association (see this question for the details). Is this index still useful? Combinations of posting_detail_type and posting_detail_id would be unique, as in only one of each would ever occur. So it seems to me that the index wouldn't be that useful.

What indexing should be used in this case? Just one on the posting_detail_type column?

Community
  • 1
  • 1
robertwbradford
  • 6,181
  • 9
  • 36
  • 61

1 Answers1

1

Yes this index is still useful.

A basic rule of thumb is any column you are querying against regularly should be indexed as it speeds up search time.

So in the case of your polymorphic association both the id and the type column should be index because whilst you will have a unique id/type pairing, you will still have multiple of the same type with different ids and visa versa which you will have to search through so speeding up search on both columns is worth while.

Hope that answers your question.

Dan Galipo
  • 268
  • 3
  • 8