Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 无法添加或更新子行:外键约束失败-Ruby on Rails_Mysql_Ruby On Rails_Ruby - Fatal编程技术网

Mysql 无法添加或更新子行:外键约束失败-Ruby on Rails

Mysql 无法添加或更新子行:外键约束失败-Ruby on Rails,mysql,ruby-on-rails,ruby,Mysql,Ruby On Rails,Ruby,我的“子”表单包含以下内容: <%= child.select :parent_id, options_for_select(Parent.all.map{ |parent| parent.grandparent.name + " - " + parent.name }, {:include_blank => true}) %> 模型看起来是这样的: class Child < ApplicationRecord belongs_to :parent end cl

我的“子”表单包含以下内容:

<%= child.select :parent_id, options_for_select(Parent.all.map{ |parent| parent.grandparent.name + " - " + parent.name }, {:include_blank => true}) %>
模型看起来是这样的:

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
class-Child:delete\u all
结束
班级祖父母<申请记录
有多个:父项,:依赖=>:全部删除
结束
在通话中,您使用的选项文本数组不正确。您需要使用成对数组[选项文本,选项值]:

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

找到了答案。是我选择的表格错了。单个选择选项的实际值不是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

类父级:delete\u all
属于:祖父母
用祖父母的名字定义父母
祖父母。姓名+“-”+姓名
结束
结束

child的复数形式是
children
——而不是
childs
。我很清楚这一点,我以英语为母语。为了这篇文章,我刚刚更改了模型名称。正如你所看到的,我找到了自己的答案,所以我现在很好。
<%= 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