将数据插入具有外键的表中

时间:2019-01-13 10:34:59

标签: mysql ruby-on-rails

我想知道如何将数据插入具有相关表外键的表中。

我正在使用Rails和MySQL。我有posts表和post_bodies表。我想使用“ accepts_nested_attributes_for”将数据插入表中。

表结构如下。

当我从Post模型插入数据时,错误提示“您需要post_body_id(FK)的默认值”。因此,我尝试为post_body_id设置数据,但错误提示“无法添加或更新子行:外键约束失败”。我想知道如何将数据插入表中。

表格

◼️posts table
id(PK)
title
post_body_id(FK)


◼️post_body_tables
id(PK)
body
post_id(FK)

型号

◼️Post
has_one :post_body
accepts_nested_attributes_for :post_body, allow_destroy: true

◼️post_body
belongs_to :post_id

控制器

◼️PostController
  def post_params
    params.permit(
                    :title,
                    :post_body_id,
                    :post_body_attributes => [:id, :post_id, :body, :_destroy]
                  )
  end

0 个答案:

没有答案
相关问题