如何保存相关模型非空的外键 [英] how to save related models with non-null foreign key

查看:275
本文介绍了如何保存相关模型非空的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号:

用户

has_one :email

电子邮件

belongs_to :user

我把email_id外键(NOT NULL)内的用户表。 现在我想将它保存在下列方式:

I put the email_id foreign key (NOT NULL) inside users table. Now I'm trying to save it in the following way:

@email = Email.new(params[:email])
@email.user = User.new(params[:user])
@email.save

这引起了分贝例外,因为外键约束不满足(NULL插入email_id)。我怎样才能优雅地解决这个还是我的数据建模错了吗?

This raises a db exception, because the foreign key constraint is not met (NULL is inserted into email_id). How can I elegantly solve this or is my data modeling wrong?

推荐答案

这应该正常工作。

@email = Email.create(params[:email])
@email.user.create(params[:user])

这篇关于如何保存相关模型非空的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆