gpt4 book ai didi

mysql - 无法添加或更新子行 : a foreign key constraint fails - Ruby on Rails

转载 作者:行者123 更新时间:2023-11-29 07:27:45 25 4
gpt4 key购买 nike

我的“子”表单包含以下选择:

<%= child.select :parent_id, options_for_select(Parent.all.map{ |parent| parent.grandparent.name + " - " + parent.name }, {:include_blank => true}) %>

在“更新”操作中,出现以下错误:

Cannot add or update a child row: a foreign key constraint fails (`database_name`.`childs`, CONSTRAINT `fk_part2_5` FOREIGN KEY (`parent_id`) REFERENCES `parents` (`id`))

模型看起来像这样:

class Child < ApplicationRecord
belongs_to :parent
end

class Parent < ApplicationRecord
has_many :childs, :dependent => :delete_all
end

class GrandParent < ApplicationRecord
has_many :parents, :dependent => :delete_all
end

最佳答案

想通了。是我选择的表格错了。各个选择选项的实际值不是 ID,因此无法更新表。想通了:

<%= child.collection_select(:parent_id, Parent.all, :id, :parent_with_grandparent_name) %>

class Parent < ActiveRecord::Base

has_many :childs, :dependent => :delete_all
belongs_to :grandparent
def parent_with_grandparent_name
grandparent.name + " - " + name
end
end

关于mysql - 无法添加或更新子行 : a foreign key constraint fails - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52976149/

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