从具有相同字段名称的第三方对象创建记录?

时间:2013-12-06 02:06:38

标签: ruby-on-rails

我的数据库中有一个Charge模型,其字段名称与第三方API返回的字段相匹配。

charge = ThirdPartyChargeAPI.find(1)

Charge.create do |e|
  e.object = charge.object
  e.paid = charge.paid
  e.amount = charge.amount
  e.currency = charge.currency
  e.refunded = charge.refunded
  e.amount_refunded = charge.amount_refunded
  e.failure_message = charge.failure_message
  e.failure_code = charge.failure_code
  e.description = charge.description
  e.metadata = charge.metadata
  e.captured = charge.captured
  e.balance_transaction = charge.balance_transaction
  e.customer = charge.customer
  e.invoice = charge.invoice
  e.created = charge.created
end
但是,似乎有点多余。有没有办法合并这个而不必手动设置每个字段?

1 个答案:

答案 0 :(得分:0)

假设没有办法从API获得直接哈希(我想会有,因为它可能以XML或JSON形式出现),你可以尝试直接映射实例变量:

Charge.create do |c|
  charge.instance_variables.each do |var| 
    value = charge.instance_variable_get(var)
    c.instance_variable_set(var, value)
  end
end

这是对你从API返回的charge的结构做了一些非常大胆的假设 - 其中包含你不想要的任何实例变量。