迁移时需要使用add_index来获取belongs_to / has_many关系吗? (Rails 3.2,Active Record)

我的问题很简单,但我找不到明确的答案。

我建立了每日优惠Rails应用程序。

  • 每笔交易都有很多产品(has_many)

  • 每个产品都属于一笔交易

从Rails指南中获取 2.3,我将在迁移中使用它:

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 

自动,Rails /活动记录会在产品表中添加一列Transactions_id对吗?

我是否需要通过添加到我的迁移add_index手动(如下所示)在此deals_id列上添加索引,还是“自动”完成,因为我设置了belongs_to / has_many关系?

 create_table :products do |t| t.belongs_to :Deal t.timestamps add_index :products, :deals_id end 

您需要自己添加索引…但是,如果您使用模型的命令行生成器并使用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 

您需要自己添加索引。

你的迁移也不太正确,你需要第3个表,即:

 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

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帮助程序可能会导致错误。