我应该删除默认" ID"利用轨道/ Postgres的一个字符串的主键时,场? [英] Should I delete the default "id" field when using a string primary key in Rails / Postgres?

查看:163
本文介绍了我应该删除默认" ID"利用轨道/ Postgres的一个字符串的主键时,场?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个构建在一个问题<一href="http://stackoverflow.com/questions/11494417/how-to-isolate-id-from-string-primary-key-in-heroku-postgres">I问前(没有任何运气)。

This is a build on a question I asked before (without any luck).

我有一个模型,我使用一个字符串作为主键:

I have a model where I'm using a string as a primary key:

class Employee < ActiveRecord::Base
   self.primary_key = "employment_id"
end 

该表还包含了Rails的默认的'身份证'领域,具有唯一性约束。

This table also contains the Rails default 'id' field, with a uniqueness constraint.

当我添加一个新员工在当地这一切工作正常,使用Rails自动生成一个新的唯一标识。

When I add a new employee locally it all works fine, with Rails automatically generating a new unique id.

然而,当我运行这个在Heroku Postgres的它似乎把'身份证'和'employment_id为同一领域。我试图解决这个问题通过手动设置一个唯一的ID,但仍获得此行为:

However when I run this on Heroku Postgres it appears to treat 'id' and 'employment_id' as the same field. I tried to get around this by manually setting a unique id, but still get this behaviour:

Employee.new do |s|

  max_id = Employee.maximum(:id)  
  puts max_id.to_s             # => 1803 

  s.employment_id = "fred_01"      
  s.id = max_id + 1 

  puts employment_id.to_s      # => 1804

end

我运行的Postgres 9.1.3本地(与Heroku的是9.1.4)。我on Rails的3.2.3。

I'm running postgres 9.1.3 locally (and Heroku is on 9.1.4). I'm on Rails 3.2.3.

我的问题是:

  • 在任何想法是怎么回事?
  • 请你认为这是正确的,我使用employment_id作为主键?
  • 倘使我删除了'身份证'字段?
  • 你有什么推荐的其他最佳做法?

感谢您的帮助!

德里克。

编辑:

根据要求添加迁移文件:

Adding migration file as requested:

class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees do |t|
      t.string :employment_id, :unique => true
      etc...
    end
  end
end

修改

很亲切没有人来指出这一点,但很明显我现在真正的答案是只因为你可以,并不意味着你应该!

Very kind of nobody to point this out, but it's clear to me now that the real answer is "Just because you can, doesn't mean you should!"

推荐答案

据<一href="http://stackoverflow.com/questions/1200568/using-rails-how-can-i-set-my-primary-key-to-not-be-an-integer-typed-column">this后,就应该解决的问题:

According to this post, it should solve the problem:

class CreateEmployees < ActiveRecord::Migration
  def change
    create_table :employees, {:id => false} do |t|
      t.string :employment_id, :unique => true
      etc...
    end
  end
  execute "ALTER TABLE employees ADD PRIMARY KEY (employment_id);"
end

另外,在你的模型:

Also in your model:

class Employee < ActiveRecord::Base
  set_primary_key :employment_id
  ...
end

这篇关于我应该删除默认&QUOT; ID&QUOT;利用轨道/ Postgres的一个字符串的主键时,场?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆