gpt4 book ai didi

ruby-on-rails - Rails 6 : Can't delete nested model. 随机插入语句

转载 作者:行者123 更新时间:2023-11-29 13:08:38 26 4
gpt4 key购买 nike

我将 Rails 6 与 Postgres 结合使用,在删除嵌套模型时遇到问题。删除关联后生成随机插入语句。

让我解释一下我的设置。

迁移

class CreateEntries < ActiveRecord::Migration[6.0]
def change
create_table :entries do |t|
t.string :name
t.timestamps
end
end
end

class Cards < ActiveRecord::Migration[6.0]
def change
create_table :cards do |t|
t.string :card_number
t.belongs_to :entry, null: true, foreign_key: true
t.timestamps
end
end
end

模型

class Entry < ApplicationRecord
has_one :card, dependent: :destroy
accepts_nested_attributes_for :card, allow_destroy: true
end

class Card < ApplicationRecord
belongs_to :entry
end

Controller

class EntriesController < ApplicationController
before_action :set_entry

def update
@entry.update(entry_params)
end

def set_entry
@entry = Entry.find(params[:id])
end

def entry_params
params.require(:entry).permit(:name,
card_attributes: [:id, :card_number, :_destroy]
)
end
end

请求参数

Parameters: {"authenticity_token"=>"CQ...Ucw==", "entry"=>{"card_attributes"=>{"_destroy"=>"true"}}, "id"=>"1"}

这些是日志

(0.2ms)  BEGIN

ConcessionCard Load (0.2ms) SELECT "cards".* FROM "cards" WHERE "cards"."entry_id" = $1 LIMIT $2 [["entry_id", 1], ["LIMIT", 1]]

Card Destroy (0.4ms) DELETE FROM "cards" WHERE "cards"."id" = $1 [["id", 2]]

Card Create (0.6ms) INSERT INTO "cards" ("entry_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["entry_id", 1], ["created_at", "2019-09-06 13:50:41.100718"], ["updated_at", "2019-09-06 13:50:41.100718"]]

(0.3ms) COMMIT

为什么在删除调用之后生成插入?这甚至不是回滚。

注意:我在 Cards belongs_to 迁移中尝试了 null:true 和 null:false。我还尝试在 Card 模型的 belongs_to :entry 语句中设置 optional:true

最佳答案

除非您在 card_attributes 中包含一个 id,否则 Rails 会将其视为一条新记录,因此它只是将 has_one 替换为新创建的Card 为你(因为你的 dependent: :destroy 选项删除了现有的关联 Card)。

最好在您的表单部分/ View 中使用 form.fields_for :card block ,它会自动为现有卡片添加隐藏的 id 标签。

关于ruby-on-rails - Rails 6 : Can't delete nested model. 随机插入语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57823864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com