How to create a relationship of a new parent with an existing child in Rails

一笑奈何 提交于 2019-12-23 03:16:20

问题


My problem is that I have a order(child record) but the user(Parent record) doesn't exist yet. And I would like to send the order as a nested attribute in the user form.

Finding the order:

@order = Order.where(:paypal_express_token => params[:token]).last

Creating the user:

@user = User.new

Trying to create the relationship

if @order.user_id.blank?
  @order.user_id = @user.id
end

But it seems that it is wrong.

When creating children and parent at the same time, I can do this:

@user = User.new
@user.build_order

Any thoughts?

UPDATE

I'm trying to to use @MrYoshiji suggestion but I found another problem that I asked in this question: Why the code doesn't appear in the html?... in Rails


回答1:


You can do as following:

@order = Order.where(:paypal_express_token => params[:token]).last
@order.user ||= User.new # ||= will set user if @order.user returns nil OR false
# ...
@order.save # should save the user also


来源:https://stackoverflow.com/questions/24087988/how-to-create-a-relationship-of-a-new-parent-with-an-existing-child-in-rails

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