使用AR和postgres来设置外键设置

时间:2016-06-09 11:21:11

标签: ruby-on-rails postgresql activerecord database-schema

我刚刚意识到删除父模型时遇到了一些问题。

我有这个设置:

user.rb

has_many :conversations, foreign_key: "sender_id", dependent: :destroy

conversation.rb

belongs_to :sender, class_name: "User", foreign_key: "sender_id"
belongs_to :recipient, class_name: "User", foreign_key: "recipient_id"

架构(postgres DB)

add_foreign_key "conversations", "users", column: "recipient_id"
add_foreign_key "conversations", "users", column: "sender_id"

您可以猜到,如果调用了user.destroy并且存在用户是收件人的对话,则会引发PG::ForeignKeyViolation ERROR: update or delete on table conversations violates foreign key constraint...

为了解决这个问题,我打算做以下事情:

user.rb

#this will solve the rails side of the problem
has_many :received_conversations, class_name: "Conversation", foreign_key: "recipient_id", dependent: :destroy

架构(DB):

#this will solve the DB side of the problem
add_foreign_key "conversations", "users", column: "recipient_id", on_delete: :cascade
add_foreign_key "conversations", "users", column: "sender_id", on_delete: :cascade

这是解决此问题的正确方法吗?

1 个答案:

答案 0 :(得分:1)

您无需在:

中提及foreign_key关系
has_many :conversations, foreign_key: "sender_id", dependent: :destroy

因为你已经在belongs_to中维护了这个关系。如果你删除了上面的外键关系,依赖:: destroy会破坏你对应的对话记录以及被删除的用户记录让它成为接收者或发送者