【问题标题】:Save additional fields to Rails child model将附加字段保存到 Rails 子模型
【发布时间】:2017-02-17 02:48:53
【问题描述】:

我有两个模型:DonorGift。我创建了has_manybelongs_to 关联。在我的DonorsController 课程中,我有 -

定义新 @donor = Donor.new 礼物 = @donor.gifts.build 结束

这是在 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

我想保存在处理付款后从 Stripe 返回的 charge.id,我正在尝试使用它 -

@donor.gifts.stripe_charge_id = charge.id(我也尝试过奇异礼物 - 没有帮助)。

@donor.save 工作得很好——包括表单上和允许列表中的礼物字段——它们都被保存到数据库中。但stripe_charge_id 字段为空白。我已经确认有一个 charge.id 值。

@donor.stripe_customer_id = customer.id 正在工作。

我将cattr_accessor :stripe_charge_id 添加到Gift 模型中。

我已经尝试定义 set/get 方法,但没有任何效果。

任何帮助将不胜感激。我在谷歌上搜索的所有内容都只是阐述了父子关联,但我对此没有任何问题。

提前致谢。

【问题讨论】:

  • @donor.gifts.stripe_charge_id = charge.id。 giftshas_many 关系,因此,您不能分配 gifts.stripe_charge_id 因为 gifts 是一个集合。您需要遍历所有礼物并将它们分配给charge.id。这是一种方式。

标签: ruby-on-rails ruby parent-child


【解决方案1】:

正如@fanta 所说,你有一个has_many 关系。所以你不能这样设置stripe_charge_id。即使你做对了,Rails 也不会仅仅因为你救了父母就救了孩子。

你可以这样做:

@donor.gifts.update_all(:stripe_charge_id => charge.id)

【讨论】:

  • 感谢您的回复。这是一种 has_many 关系,因为捐赠者可能拥有不止一份礼物,但每笔交易都有一份。其他礼物字段在没有任何额外代码的情况下保存在捐赠者保存方法中,所以我想我可以在保存捐赠者之前添加 stripe_charge_id。但是我在保存捐赠者之后调用了 update_all 函数,并且做到了。再次感谢。
  • 嗨 - 我投票了,但我的分数仍然太低,无法反映在分数中 - 抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-11
相关资源
最近更新 更多