重要使用SQLite3上唯一的組合鍵索引將其記錄到連接表中。請注意,對於我所做的所有(手動)測試,數據庫已通過db:drop,然後是db:migrate完全重建。不能添加記錄的連接表在Rails的複合唯一索引3.2
錯誤:
ActiveRecord::RecordNotUnique
SQLite3::ConstraintException: columns adventurer_id, item_id are not unique:
INSERT INTO "adventurers_items" ("adventurer_id", "item_id") VALUES (1, 68)
生成錯誤代碼:
class Adventurer < ActiveRecord::Base
after_create :set_starting_skills
after_create :set_starting_items
has_and_belongs_to_many :items
has_and_belongs_to_many :skills
# automatically add starting skills on creation
def set_starting_skills
self.skills = self.profession.starting_skills
end
# automatically add starting items on creation
def set_starting_items
self.items = self.profession.items
end
遷移創建連接表adventurers_skills:
class AdventurersItems < ActiveRecord::Migration
def change
create_table :adventurers_items do |t|
t.integer :item_id, :null => false
t.integer :adventurer_id, :null => false
end
add_index :adventurers_items, :item_id
add_index :adventurers_items, :adventurer_id
add_index :adventurers_items, [:adventurer_id, :item_id], :unique => true
該表存在且完全爲空。由於唯一性約束,爲什麼我的應用程序無法插入此記錄?我也有同樣的表「adventurers_skills」的錯誤 - 我在建築上做錯了什麼?
編輯
該系統正試圖添加同一項目/技能的兩倍。當我將私有方法更改爲:
def set_starting_skills
skills = profession.starting_skills
end
它不會嘗試在連接表中創建任何內容。但恢復的第一行如下self.skills試圖創建具有相同技能TWICE
def set_starting_skills
self.skills = profession.starting_skills
end
回報
(0.4ms) INSERT INTO "adventurers_skills" ("adventurer_id", "skill_id") VALUES (4, 54)
(4.9ms) INSERT INTO "adventurers_skills" ("adventurer_id", "skill_id") VALUES (4, 54)
SQLite3::ConstraintException: columns adventurer_id, skill_id are not unique:
INSERT INTO "adventurers_skills" ("adventurer_id", "skill_id") VALUES (4, 54)
(3.2ms) rollback transaction
只有一個技能返回profession.starting_skills
:所以
1.9.3-p194 :022 > Profession.find(7).starting_skills.each {|x| puts x.id}
54
真正的問題變成了:爲什麼Rails試圖添加這個HABTM記錄兩次?
請向我們展示給出該錯誤的代碼。模型和遷移並不實際插入數據。不過,還有其他的東西。所以請告訴我們「其他」 – 2013-03-02 15:15:53
嗯有一個錯誤調用回調方法兩次,因此它試圖插入一個項目兩次。 – DrFunk 2013-03-02 15:45:19
那麼,你解決了這個問題嗎?因爲我變得完全一樣。 – dukedave 2013-07-19 20:40:13