首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Heroku,Postgresql,composite_primary_keys

Heroku,Postgresql,composite_primary_keys
EN

Stack Overflow用户
提问于 2012-05-31 21:55:35
回答 1查看 667关注 0票数 2

我有一个Rails 3应用程序,我正在工作。我对几个表使用了composite_primary_keys gem,但是Rails仍然在创建一个未被使用的id字段(即对于每个条目它是零)。当它在SQLite3的本地机器上运行时,我不能在Heroku上运行这个应用程序。Postgresql对我大发雷霆,并给出了以下错误:

代码语言:javascript
复制
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并重写代码。

模型

代码语言:javascript
复制
class ItemAttrQuant < ActiveRecord::Base
  belongs_to :item
  belongs_to :attribute
  self.primary_keys = :item_id, :attribute_id
end

迁移

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-31 22:50:49

您可以在迁移中使用:id => false:primary_key选项create_table

代码语言:javascript
复制
class CreateItemAttrQuants < ActiveRecord::Migration
  def change
    create_table :item_attr_quants, :id => false do |t|
      ...
    end
    ...
  end
end

这将在没有id列的情况下创建id,但您的表将没有真正的主键。您可以通过为item_idattribute_id指定item_idattribute_id并在这两列上添加唯一索引来添加假索引:

代码语言:javascript
复制
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。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10841834

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档