0

I am create an active record association that I use in a form. I have two models and one form. I am creating a customer_order and payment at the same time. That all works as planned, what I am having trouble with is I want to add the user_id to the Payments table, it adds it to the customer_order perfectly.

@customer_order.payments.build(:payment_amt => @mailer.full_price, :user_id => current_user.id)

When I click the create on the form, I am losing the user_id. I understand that I do not want to store the user_id in a hidden field in the form. But when the program hits the create. I would like to either add the user_id before the save (ideally) or after.

I am able to save it in the customer_order, but not sure how to save it in the Payment table.

@customer_order.user_id = current_user.id

@customer_order.save

I am a rails newbie so go easy on me.

cih
  • 1,960
  • 1
  • 16
  • 27
ja11946
  • 177
  • 1
  • 2
  • 13
  • You probably need to include a hidden field in the form. But I won't know unless you include more information. Please include full controller code and form view code. – Peter P. Nov 05 '15 at 23:36

1 Answers1

0

If @customer_order.payments.build(:payment_amt => @mailer.full_price, :user_id => current_user.id) is in your new controller action then you are not persisting it so the attribute user_id is being set and can be accessed by the form builder when rendering the new template. When you submit the form you are making a new request so will need to use a hidden field to submit the user_id param back up to the create action.

That being said if you're only interested in creating a payment for the current_user then you can just associate the user in the create action too.

If all of the code above is in the create action then the payment should also be saved when calling save on the parent of the has_many association, more info can be found here

Community
  • 1
  • 1
cih
  • 1,960
  • 1
  • 16
  • 27