[英]Rails two models one form how to add a field to the second model
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. 我要同时创建一个customer_order
和payment
。 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. 所有这些都按计划进行,我遇到的麻烦是我想将user_id添加到Payments表中,并将其完美地添加到customer_order中。
@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
. 当我单击表单上的create时,我丢失了user_id
。 I understand that I do not want to store the user_id in a hidden field in the form. 我知道我不想将user_id存储在表单的隐藏字段中。 But when the program hits the create. 但是当程序点击创建时。 I would like to either add the user_id
before the save (ideally) or after. 我想在保存之前(理想情况下)或之后添加user_id
。
I am able to save it in the customer_order
, but not sure how to save it in the Payment
table. 我能够将其保存在customer_order
,但是不确定如何将其保存在Payment
表中。
@customer_order.user_id = current_user.id
@customer_order.save
I am a rails newbie so go easy on me. 我是Rails新手,所以请放轻松。
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. 如果在新的控制器操作中使用@customer_order.payments.build(:payment_amt => @mailer.full_price, :user_id => current_user.id)
,则您将不会保留该属性,因此可以设置属性user_id
,并且可以通过呈现新模板时的表单生成器。 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. 提交表单时,您正在发出新请求,因此需要使用一个隐藏字段来将user_id
参数提交回create动作。
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. 话虽这么说,如果您只想为current_user
创建付款,那么您也可以将用户关联到create动作中。
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 如果上面的所有代码都在create动作中,则在has_many
关联的父级上调用save时,也应该保存付款,有关更多信息,请参见此处
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.