141

Productsテーブルがあり、列を追加したい:

t.references :imageable, :polymorphic => true

私はこれを行うことで移行を生成しようとしていました:

$ rails generate migration AddImageableToProducts imageable:references:polymorphic

しかし、私は明らかにそれを間違っています。誰か提案できますか?ありがとう

移行を生成した後に手動で挿入しようとすると、次のようになりました。

class AddImageableToProducts < ActiveRecord::Migration
  def self.up
    add_column :products, :imageable, :references, :polymorphic => true
  end

  def self.down
    remove_column :products, :imageable
  end
end

そしてそれはまだ機能していません

4

4 に答える 4

303

あなたがやろうとしていることはまだ安定版のレールに実装されていないので、ミシェルの答えは今のところ正しいものです。ただし、この機能はRails 4に実装され、次のようにエッジバージョンですでに利用可能です(このCHANGELOGによる)。

$ rails generate migration AddImageableToProducts imageable:references{polymorphic}
于 2013-03-04T15:02:12.737 に答える
120

Rails 4より前は、ポリモーフィックアソシエーション用の組み込みジェネレーターはありませんでした。Railsの初期バージョンを使用している場合は、空白の移行を生成し、必要に応じて手動で変更します。

更新:変更するテーブルを指定する必要があります。このSOの答えによると:

class AddImageableToProducts < ActiveRecord::Migration
  def up
    change_table :products do |t|
      t.references :imageable, polymorphic: true
    end
  end

  def down
    change_table :products do |t|
      t.remove_references :imageable, polymorphic: true
    end
  end
end

Rails 4は、ポリモーフィックな関連付けのためのジェネレーターを追加しました(simon-olivierの回答を参照)

于 2011-04-04T04:38:50.377 に答える
47

次のこともできます。

class AddImageableToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :imageable, polymorphic: true, index: true
  end
end
于 2014-11-24T21:38:27.913 に答える
18

あなたが試すことができますrails generate migration AddImageableToProducts imageable:references{polymorphic}

于 2017-09-13T07:17:40.067 に答える