how to save related models with non-null foreign key

为君一笑 提交于 2019-12-11 17:36:26

问题


I have two models:

User

has_one :email

Email

belongs_to :user

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

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?


回答1:


This should work as expected.

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



回答2:


Hum... Do you have

has_one :email

in your user model?

If it's the case, I think there is a problem. You should use has_one in the user model if it's the email table that has the foreign_key.

You should have a user_id column in the email table I think.



来源:https://stackoverflow.com/questions/4912154/how-to-save-related-models-with-non-null-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!