Question

After a few hours of working in a new rails project i successfully configured a has_many :thru association with the following migration

class CreateEdits < ActiveRecord::Migration
  def change
    create_table :edits do |t|
      t.references :user
      t.references :post
      t.string :action
      t.text :summary
      t.timestamps
    end
  end
end

Now after reading further on the topic discovered that apparently i should have added

add_index :edits, [:user_id, :post_id], unique: true

But the rails guides on this topic mention nothing about the need to index these columns. So id like to know if theres really a need for me to create a new migration to add such indexes. I'm new in the whole rails and coding thing so i'd love to know if this would be essential in a production environment or not,as for me to become accustomed to the best practices along the way.

Thanks in advance.

Was it helpful?

Solution

Basically there is no need to index any column. Your Rails application itself won't need them. However, they are (usually) necessary for your database to perform well.

What you usually do in Rails right from the beginning is to index all of your {...}_id columns, because these columns will be used to query associations.

In the end you have to fine-tune database indexes depending on how your application is querying for data and what are key columns. Keep in mind, that adding to many indexes can slow your database down.

See also Rails 3 Databases Indexes And Other Optimization

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top