问题
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