2014-09-12 106 views
1

我與這個post相同的問題。但我使用Rails,並不知道如何在activerecord中執行此解決方法。Rails + postgres自動增量沒有更新顯式ID插入

device_platforms = DevicePlatform.create([{id: 1, name: 'Android'}, {id: 2, name: 'IOS'}, {id: 3, name: 'Windows Phone'}]) 

當我插入另一DevicePlatform,我得到這個異常:

Failure/Error: @device_platform = FactoryGirl.create(:device_platform) 
ActiveRecord::RecordNotUnique: 
    PG::UniqueViolation: ERRO: duplicar valor da chave viola a restrição de unicidade "device_platforms_pkey"                 
    DETAIL: Chave (id)=(2) já existe. 
    : INSERT INTO "device_platforms" ("created_at", "name", "updated_at") VALUES ($1, $2, $3) RETURNING "id"   

的消息是葡萄牙語,它說,一個

我使用seeds.rb插入一些數據具有該ID的行已經存在。

謝謝。

+0

你爲什麼指定ID? – 2014-09-12 17:32:27

+0

我不確定你的意思,你正在調用'create',所以你要「去數據庫」。如果在種子創建調用中只有'{name:'Android'},{name:'IOS'}等,那麼你的代碼會不起作用? – 2014-09-12 17:35:24

+0

不要在種子中包含「id」。如果你必須在你的種子中包含'id's,那麼在添加種子後,你必須在另一個問題中'connection.execute' SQL。 – 2014-09-12 17:40:13

回答

0

根據評論,在種子中使用id是一種不好的做法。我避免了不好的做法,這對我來說已經足夠了。改變了我的代碼以避免這種情況。