Rails 4:活动记录集合循环或迭代

时间:2016-01-28 09:22:39

标签: ruby-on-rails braintree

在我的rails客户控制器中有一个活动的记录集合对象:

1。 @pay_invoices = Invoice.where(customer_id:@pay_cus_id)

#<ActiveRecord::Relation [#<Invoice id: 37, customer_id: 53, paid_amount: 960, devicemodel_id: 2, transaction_id: "6drv3s", created_at: "2016-01-04 05:29:03", updated_at: "2016-01-25 12:16:14">, #<Invoice id: 70, customer_id: 53, paid_amount: 80, devicemodel_id: 2, transaction_id: "2mr93s", created_at: "2016-01-28 09:02:43", updated_at: "2016-01-28 09:02:43">]>

同样在我的控制器中,我使用 transaction_id:列值,使用以下Braintree API调用在Braintree支付网关中查找交易详情:

 @tid = @pay_invoices[0].transaction_id

 @transaction = Braintree::Transaction.find(@tid)

这对我来说很好,但是只能使用此代码检索 @pay_invoices 集合中第一个 transaction_id:的交易详情,我想要迭代 @pay_invoices 集合以及每次我想将braintree交易详细信息存储到另一个集合中时,只有我可以在我的视图中显示每笔交易的付款详细信息。

如何实现它?

1 个答案:

答案 0 :(得分:0)

transaction_ids = Invoice.where(customer_id: @pay_cus_id).pluck(:transaction_id)
@transactions = []
transaction_ids.each do |t_id|
  @transactions << Braintree::Transaction.find(t_id)
end

虽然如果有相同的地方,你可以简单地做一些像

transaction_ids = Invoice.where(customer_id: @pay_cus_id).pluck(:transaction_id)
@transactions = Braintree::Transaction.where(transaction_id: transaction_ids)