Need to use add_index for migration for belongs_to / has_many relationships? (Rails 3.2 active record)

My question is pretty simple, but I did not find a clear answer.

I am creating a daily Rails deals application.

  • Each transaction has many products (has_many)

  • Each product belongs to a transaction.

Hit 2.3 from Rails Guides , I will use this in my migration:

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 end end 

Automatically, Rails / active records will add the deal_id column to the product table correctly?

Do I need to add an index to this deal_id column manually (for example, below), adding add_index to my migration add_index or is it done "automatically" due to the belongs_to / has_many relationship that I established?

 create_table :products do |t| t.belongs_to :Deal t.timestamps add_index :products, :deals_id end 
+6
source share
3 answers

You need to add the index yourself ... However, if you use the command line generator for the model and use belongs_to, Rails will add to the index in the transfer ...

eg.

 rails g model product deal:belongs_to 

will create

 class CreateProducts < ActiveRecord::Migration def change create table :products do |t| t.belongs_to :deal t.timestamps end add_index :products, :deal_id end end 
+12
source

You will need to add indexing yourself.

Also your migration is not quite right, you need a 3rd table, i.e.

 class CreateDeal < ActiveRecord::Migration def change create_table :deals do |t| t.string :name t.timestamps end create_table :products do |t| t.string :title t.timestamps end create_table :deals_products do |t| t.belongs_to :deal t.belongs_to :product end end end 

According to http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

+2
source

Mathieu, in such situations where you are not sure that something is being created or not being created: it is best to just create what you think is necessary (in this case, an index) and see what happens when the migration starts.

The logic behind this is that if your :deal_id column :deal_id already indexed and your migration tries to reindex it, it will receive an error message and the migration will be canceled so you can fix it. However, if you did not add the index to your migration, you obviously will not get any errors, but you will need to take an additional 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 is complete. Using the add_index helper inside the create_table helper is likely to result in an error.

+1
source

Source: https://habr.com/ru/post/953386/


All Articles