[英]Save additional fields to Rails child model
I have two models: Donor
and Gift
. 我有两个模型:
Donor
和Gift
。 I've created has_many
and belongs_to
associations. 我创建了
has_many
和belongs_to
关联。 In my DonorsController
class, I have - 在
DonorsController
类中,我有-
def new @donor = Donor.new gift = @donor.gifts.build end def new @donor = Donor.new礼物= @ donor.gifts.build结束
This is defined in DonorsController - 这在DonorsController中定义-
def create
@donor = Donor.new(donation_params)
... etc....
end
private
def donation_params
params.require(:donor).permit(:first_name, :last_name, :address_1, :address_2, :city, :state, :zip, :email, :phone, gifts_attributes: [:amount, :frequency])
end
I want to save the charge.id
that I get back from Stripe after processing a payment, I'm trying it with this - 我想保存在处理付款后从Stripe取回的
charge.id
,我正在尝试这样做-
@donor.gifts.stripe_charge_id = charge.id
(I also tried singular gift - didn't help). @donor.gifts.stripe_charge_id = charge.id
(我也尝试过单数礼物-没有帮助)。
@donor.save
works just fine - including the gift fields that are on the form and in the permitted list - they all get saved to the db. @donor.save
可以很好地工作-包括表单上和允许列表中的礼物字段-它们都保存到数据库中。 But the stripe_charge_id
field is blank. 但是
stripe_charge_id
字段为空。 I've confirmed there is a charge.id
value. 我已经确认有一个
charge.id
值。
@donor.stripe_customer_id = customer.id
is working. @donor.stripe_customer_id = customer.id
正在运行。
I added cattr_accessor :stripe_charge_id
to the Gift
model. 我向
Gift
模型添加了cattr_accessor :stripe_charge_id
。
I've tried defining set/get methods, nothing is working. 我尝试定义set / get方法,但没有任何效果。
Any help would be appreciated. 任何帮助,将不胜感激。 Everything I've googled just expounds on parent & child associations, but I don't have any problems with that.
我用Google搜索的所有内容都只是说明了父母与孩子的关联,但是我对此没有任何问题。
Thanks in advance. 提前致谢。
As @fanta said, you have a has_many
relation. 正如@fanta所说,您具有
has_many
关系。 So you cannot set the stripe_charge_id
like that. 因此,您不能像这样设置
stripe_charge_id
。 And even if you did it right, rails would not save the child just because you saved the parent. 即使您做对了,Rails也不会仅仅因为您保存了父母而保存了孩子。
You could do this: 您可以这样做:
@donor.gifts.update_all(:stripe_charge_id => charge.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.