7

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)

  • Each product belongs to a deal

Folowing 2.3 from Rails Guides, I'll 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 in the Product Table a column deals_id right?

Do I need to add an index on this deals_id column manually (like below) by adding to my migration add_index or is it done "automatically" because of the belongs_to/has_many relationship I have set?

create_table :products do |t|
  t.belongs_to :Deal
  t.timestamps

  add_index :products, :deals_id 
end
4

3 回答 3

13

您确实需要自己添加索引...但是,如果您使用模型的命令行生成器并使用belongs_to,Rails 会将索引添加到迁移中...

例如

rails g model product deal:belongs_to

会产生

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
于 2013-09-07T14:10:16.500 回答
2

您需要自己添加索引。

此外,您的迁移也不太正确,您需要第三张表,即:

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

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

于 2013-09-07T12:38:03.123 回答
1

Mathieu,在这种有疑问的情况下,您不确定是否正在创建某些东西:似乎最好只明确创建您认为需要的内容(在本例中为索引),然后查看运行时会发生什么迁移。

这背后的逻辑是,如果您的:deal_id列已经被索引并且您的迁移尝试重新索引它,它将得到一个错误并且迁移将回滚以便您可以修复它。但是,如果您没有在迁移中添加索引,您显然不会收到任何错误,但您必须采取额外的步骤来检查索引是否存在。

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

请注意,您还希望在表创建过程完成后添加索引。在 create_table 助手中使用 add_index 助手可能会导致错误。

于 2013-09-07T15:08:14.477 回答