2

作業中のRails3アプリがあります。いくつかのテーブルにcomposite_primary_keysgemを使用していますが、Railsはまだ使用されていないidフィールドを作成しています(つまり、エントリごとにnilです)。SQLite3のローカルマシンで実行されていますが、Herokuでアプリを実行できません。Postgresqlは私にフィットを投げ、私にこのエラーを与えます:

2012-05-31T21:12:36+00:00 app[web.1]: ActiveRecord::StatementInvalid (PG::Error: ERROR:  null value in column "id" violates not-null constraint
2012-05-31T21:12:36+00:00 app[web.1]:   app/controllers/items_controller.rb:57:in `block (2 levels) in create'
2012-05-31T21:12:36+00:00 app[web.1]: : INSERT INTO "item_attr_quants" ("attribute_id", "created_at", "id", "item_id", "updated_at", "value") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "item_id","attribute_id"):

「id」フィールドはnilなので、Postgresqlは私に怒鳴ります。

そもそも「id」フィールドが作成されないようにする方法、生のSQLステートメントを使用して列を削除する方法、HerokuのPostgresqlに「id」フィールドをnullに許可する方法、またはこれを回避する方法はありますか?仕方?複合主キーの使用に行き詰まっているので、gemを削除してコードを書き直したくありません。

モデル

class ItemAttrQuant < ActiveRecord::Base
  belongs_to :item
  belongs_to :attribute
  self.primary_keys = :item_id, :attribute_id
end

移行

class CreateItemAttrQuants < ActiveRecord::Migration
  def change
    create_table :item_attr_quants do |t|
      t.belongs_to :item
      t.belongs_to :attribute
      t.integer :value

      t.timestamps
    end
    add_index :item_attr_quants, :item_id
    add_index :item_attr_quants, :attribute_id
  end
end
4

1 に答える 1

1

移行では、:id => falseおよび:primary_keyオプションを使用できます。create_table

class CreateItemAttrQuants < ActiveRecord::Migration
  def change
    create_table :item_attr_quants, :id => false do |t|
      ...
    end
    ...
  end
end

item_attr_quantsこれは列なしで作成されidますが、テーブルには実際の主キーがありません。not nullforitem_idを指定しattribute_id、これら2つの列に一意のインデックスを追加することで、偽のインデックスを追加できます。

class CreateItemAttrQuants < ActiveRecord::Migration
  def change
    create_table :item_attr_quants, :id => false do |t|
      t.integer :item_id, :null => false
      t.integer :attribute_id, :null => false
      t.integer :value
      t.timestamps
    end
    add_index :item_attr_quants, [:item_id, :attribute_id], :unique => true
    add_index :item_attr_quants, :item_id
    add_index :item_attr_quants, :attribute_id
  end
end

ActiveRecordがデータベース内の実際の複合主キーの概念を完全に理解しているとは思わないので、ALTER TABLEをデータベースに手動で送信する場合を除いて、一意のインデックスがAFAIKで最善の方法です。

于 2012-05-31T22:50:49.410 に答える