Я получаю сообщение об ошибке несоответствия внешнего ключа:
ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_5b5ddfd518" on table "posts"
DETAIL: Key (id)=(950961012) is still referenced from table "posts".
Итак, моя таблица сообщений ссылается на запись в таблице пользователей, но когда пользователь удаляется, я не хочу, чтобы сообщения пользователя удалялисьтакже.Итак, что происходит: по-прежнему есть ссылка на пользователя, которого не существует.
Я хочу, чтобы это отношение было разорвано при удалении пользователя и сохранить сообщение пользователя, возможно, сделав ссылку на пользователя nil
Вот выдержка из моего schema.rb
create_table "posts", force: :cascade do |t|
t.bigint "user_id"
t.string "title"
t.text "body"
t.string "category"
t.string "slug"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["category"], name: "index_posts_on_category"
t.index ["slug"], name: "index_posts_on_slug", unique: true
t.index ["user_id"], name: "index_posts_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "slug"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.datetime "reset_sent_at"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["name"], name: "index_users_on_name", unique: true
t.index ["slug"], name: "index_users_on_slug", unique: true
end
user.rb :
class User < ApplicationRecord
...
has_many :posts
...
post.rb :
class Post < ApplicationRecord
...
belongs_to :user
...
end