我正在建設一個軌道網站,其中涉及一個定向的友誼關係。我知道在模型層面上,它是一個自我參照關聯。並且有關於該關聯的方法如has_and_belongs_to
。軌道數據庫約束自我指涉關聯
我的問題是:如何爲這個關係設置數據庫級別約束。我猜的遷移會是這樣的,它使用外鍵,以保證參照完整性:
class CreateFriendships < ActiveRecord::Migration
def change
create_table :friendships do |t|
t.belongs_to :user, null: false, foreign_key: true
t.belongs_to :user, null: false, foreign_key: true
t.integer :accepted, null: false, default: 0
end
end
但是當我運行rake db:migrate
,它的主要錯誤:
PG::DuplicateObject: ERROR: constraint "fk_friendships_user_id" for relation "friendships" already exists
由於事實上,我甚至不確定是否有必要在這種情況下設置數據庫約束,因爲我看到一些人的友誼關係的實現沒有這樣的數據庫約束:
create_table :friendships do |t|
t.integer :user_id
t.integer :friend_id
t.timestamps
end
根據Rails的指南
The Active Record way claims that intelligence belongs in your models, not in the database. As such, features such as triggers or constraints, which push some of that intelligence back into the database, are not heavily used.
我不知道是否在這種情況下,數據庫約束大量使用。
因此,在這種情況下,我真的需要設置數據庫級別約束(使用外鍵)嗎?或者我只需要認識模型層面的約束條件?謝謝!!
你說它不起作用。什麼不行?在執行特定操作後是否收到特定的錯誤消息? –
感謝您的評論。我已將該錯誤消息添加到我的問題中。 –