2012-07-20 42 views
0

這是建立在問題I asked before(沒有任何運氣)。在Rails/Postgres中使用字符串主鍵時,我應該刪除默認的「id」字段嗎?

我有哪裏我使用一個字符串作爲主鍵的模式:

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

此表還包含了Rails默認的「ID」字段,具有唯一性約束。

當我在本地添加一個新員工時,它一切正常,Rails自動生成一個新的唯一ID。

但是,當我在Heroku Postgres上運行它時,它將'id'和'employment_id'視爲同一個字段。我試圖通過手動設置一個唯一的ID來解決這個問題,但仍獲得此行爲:

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)。我在Rails 3.2.3上。

我的問題是:

  • 任何想法是怎麼回事?
  • 您認爲我正在使用employment_id作爲主鍵嗎?
  • 如果我刪除'id'字段會有幫助嗎?
  • 有什麼其他的最佳做法,你會推薦?

感謝您的幫助!

德里克。

編輯:根據要求

添加遷移文件:

編輯

很親切的人的指出這一點,但現在已經清楚,我認爲真正的答案是「只因爲你可以,並不意味着你應該!」

+0

難道你把':ID => FALSE'上遷移,創建表和模型時? – MurifoX 2012-07-20 13:54:01

+0

或者你可以看看這個問題:http://stackoverflow.com/questions/1200568/using-rails-how-can-i-set-my-primary-key-to-not-be-an-integer-typed -column – MurifoX 2012-07-20 13:55:13

+0

請註明您遷移文件在這裏。 – gabrielhilal 2012-07-20 14:21:40

回答

1

this後,就應該解決的問題:

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 

而且在你的模型:

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

偉大的東西。非常感激! – 2012-07-20 14:47:25

+0

如果您使用rails 3.2或更高版本,則不建議使用set_primary_key方法。 Rails 3.2發佈說明 - 第8.1節,它建議使用賦值方法,而不是像「self.primary_key =:employment_id」 – 2016-02-22 19:33:41

0

更新爲Rails 4.2.0和Postgres的情況下,它可以幫助任何人.. 。

把一個id: :stringcreate_table選項:

class FooMigration < ActiveRecord::Migration 
    def change 
    create_table :foo, id: :string do |t| 
     t.string :name, null: false 
     t.timestamps null: false 
    end 
    end 
end 

耙分貝:遷移

== 20150225043441 FooMigration: migrating =========================== 
-- create_table(:foo, {:id=>:string}) -> 0.0031s 
== 20150225043441 FooMigration: migrated (0.0032s) ================== 

軌分貝(和\ d富)

psql (9.3.6) 
Type "help" for help. 

bar_development=# \d foo 
        Table "public.foo" 
    Column |   Type    | Modifiers 
------------+-----------------------------+----------- 
id   | character varying   | not null 
name  | character varying   | not null 
created_at | timestamp without time zone | not null 
updated_at | timestamp without time zone | not null 
Indexes: 
    "foo_pkey" PRIMARY KEY, btree (id) 

我結束了一個'not null'帶有主鍵索引的字符串列。

使用比id其他列名的更復雜。

編輯(2015年2月26日):似乎有在軌道中的錯誤時,它產生的schema.rb文件。它不會記錄自定義主鍵狀態,您需要進入並編輯它以將id: :string選項添加到create_table呼叫。

即。

create_table "foo", id: :string, force: :cascade do |t| 
    t.string "name",  null: false 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

蹩腳的部分:每次進行遷移時,這種變化都將被撤消。你必須密切關注文件內容(或者寫一個測試:))。

的BUG在PR 18228,合併軌道:主於1月3日,2015年

相關問題