2

我有一个正在开发的 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
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_idattribute_id在这两列上添加唯一索引来添加假的:

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 完全理解数据库中真正的复合主键的概念,因此唯一索引是 AFAIK 最好的,除非您想手动将 ALTER TABLE 发送到数据库中。

于 2012-05-31T22:50:49.410 回答