7

私の質問は非常に単純ですが、明確な答えを見つけることができませんでした。

日替わりの Rails アプリを作成しています。

  • 各取引には多くの製品があります (has_many)

  • 各製品は取引に属します

Rails Guidesの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/active レコードは Product テーブルに deal_id 列を追加しますよね?

この deal_id 列に手動で (以下のように) インデックスを追加する必要がありますか (以下のように) 移行に追加しadd_indexますか? それとも、belongs_to/has_many 関係が設定されているため、「自動的に」行われますか?

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

自分でインデックスを追加する必要があります。

また、移行が正しくないため、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に従って

于 2013-09-07T12:38:03.123 に答える