2016-08-18 158 views
-1

期間唯一約束如何避免Duplicate key value violates unique constraint重複鍵值違反rspec的

我認爲id:1已在使用,但我需要強烈設置id

,因爲我有方法category模型

def iconic 
    case self.id 
     when 1 
     smth 
    .... 
    end 
end 

我的工廠

FactoryGirl.define do 
    factory :category do 
    sequence(:title) { |n| Faker::Hipster.word+"#{n}" } 
    position 1 
    text Faker::Lorem.sentence 
    image File.open(Rails.root.join('test', 'assets', 'images', 'banners', (1..6).to_a.sample.to_s+'.png')) 

    end 
end 

Failure/Error: c1 = create(:category, id: 1) 

ActiveRecord::RecordNotUnique: 
    PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "categories_pkey" 
    DETAIL: Key (id)=(1) already exists. 
+0

什麼是實際使用情況? – max

回答

1

是的問題是,你正試圖創建多個記錄具有相同的值id屬性,這是不允許的。它應該永遠是獨一無二的。

實際的問題是我認爲你的型號代碼是依賴於對象的id

def iconic 
    case self.id 
    when 1 
    smth 
    .... 
    end 
end 

這不是寫基於id屬性的邏輯,因爲當你不能確保相同的ID將被分配到同一個對象每次你填充數據庫一個很好的做法。相反,你應該使用其他一些獨特的屬性,如slug,email,username,無論適合你的模型。所以,你應該修改你的模型邏輯是這樣的:

def iconic 
    case self.slug_or_any_other_unique_field 
    when 'expected_value_of_above_field' 
     smth 
     .... 
    end 
end 
相關問題