Ruby on rails 是否需要在迁移时为“属于/拥有”多个关系使用“添加索引”?(Rails 3.2,活动记录)

Ruby on rails 是否需要在迁移时为“属于/拥有”多个关系使用“添加索引”?(Rails 3.2,活动记录),ruby-on-rails,ruby,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,我的问题很简单,但我没有找到明确的答案 我构建了一个每日交易Rails应用程序 每笔交易都有很多产品(有很多) 每种产品都属于一笔交易 下面是中的2.3,我将在迁移中使用它: class CreateDeal < ActiveRecord::Migration def change create_table :deals do |t| t.string :name t.timestamps end cr

我的问题很简单,但我没有找到明确的答案

我构建了一个每日交易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

您需要自己添加索引

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

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
class CreateDeal

根据

您确实需要自己添加索引。。。但是,如果您对模型使用命令行生成器并使用“所属对象”,Rails将在迁移中添加索引

e、 g

会产生

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
class CreateProducts
Mathieu,在这种怀疑的情况下,您不确定是否正在创建某些内容:最好只显式地创建您认为需要的内容(在本例中为索引),并查看运行迁移时会发生什么

这背后的逻辑是,如果您的
:deal\u 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
class CreateDeal

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

这是多对多关系的设置,而不是Mathieu所说的简单has\u many关系。我个人会避免这种设置,除非您真的需要多对多关联,因为在这种设置中,您有3个表需要2个索引(这在这次迁移中被忽略),而不是2个表和一个索引。据我所知,虽然索引加快了查询速度,但它们会使保存/更新过程花费更长的时间,所以通常最好将它们的使用最小化,以便仅在需要它们时减少开销。在这种情况下,似乎一个索引就足够了。是的,我的错误-我不知道我从哪里得到的,他使用的是多对多。不应该
t.begins\u to:Deal
be
t.begins\u to:Deal
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
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