我有一个正在开发的 Rails 3 应用程序。我在几个表中使用了composite_primary_keys gem,但是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”字段为零,Postgresql 对我大喊大叫。
有没有一种方法可以防止首先创建“id”字段,使用原始 SQL 语句删除列,强制 Heroku 上的 Postgresql 允许“id”字段为空,或者解决这个问题方法?我对使用复合主键很执着,所以我不想删除 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