我有一个Rails 3应用程序,我正在工作。我对几个表使用了composite_primary_keys gem,但是Rails仍然在创建一个未被使用的id字段(即对于每个条目它是零)。当它在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“字段是0,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发布于 2012-05-31 22:50:49
您可以在迁移中使用:id => false和:primary_key选项create_table:
class CreateItemAttrQuants < ActiveRecord::Migration
def change
create_table :item_attr_quants, :id => false do |t|
...
end
...
end
end这将在没有id列的情况下创建id,但您的表将没有真正的主键。您可以通过为item_id和attribute_id指定item_id和attribute_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。
https://stackoverflow.com/questions/10841834
复制相似问题