Need to use add_index on migration for belongs_to/has_many relationship? (Rails 3.2, Active Record)

前端 未结 3 630
心在旅途
心在旅途 2021-01-02 17:13

My question is quite simple but I failed to find a clear answer.

I build a daily deals Rails app.

  • Each deal has many products (has_many)

3条回答
  •  渐次进展
    2021-01-02 17:52

    Mathieu, in situations of doubt like this, where you're not sure if something is being created or not created: it seems best to just explicitly create what you think is needed (in this case the index) and see what happens when you run the migration.

    The logic behind this is that if your :deal_id column is already indexed and your migration tries to re-index it, it will get an error and the migration will rollback so you can fix it. However if you didn't add the index in your migration, you would obviously not get any errors but you'd have to take an extra step to check if the index exists.

    class CreateDeal < ActiveRecord::Migration
      def change
        create_table :deals do |t|
          t.string :name
          t.timestamps
        end
    
        create_table :products do |t|
          t.belongs_to :Deal
          t.timestamps
        end
    
        add_index :products, :deal_id
      end
    end
    

    Note that you also want to add the index after the table creation process has complete. Using the add_index helper inside the create_table helper is probably going to cause an error.

提交回复
热议问题