我需要在Ruby on Rails应用程序中合并到不同的对象。我有我的发票对象:
class Invoice < ActiveRecord::Base {
:id => :integer,
:user_id => :integer,
:description => :text,
......
:status => :string,
:price => :float
}
我的付款对象:
class Payment < ActiveRecord::Base {
:id => :integer,
:token => :string,
:invoice_id => :integer,
:created_at => :datetime,
:updated_at => :datetime,
:email => :string
}
他们之间有1对多的关系:
class Invoice < ActiveRecord::Base
has_many :payments
class Payment < ActiveRecord::Base
belongs_to :invoice
现在我要做的是返回Invoice对象和相关付款对象的:email和:created_at字段。现在我用zip函数返回两个对象:
:invoices => (user.invoices.where(:hide => false).zip user.invoices.map{|x| x.payments.last}),
但返回一个数组数组:
[
[{invoice},{payment}],
[{invoice},{payment}],
...
]
我想要归还的是:
[
{invoice, :email_payment, :created_at_payment},
{invoice_1, :email_payment, :created_at_payment},
...
]
我该怎么做?
答案 0 :(得分:2)
我会将email_payment
和created_at_payment
添加为发票模型的方法,但您可以通过以下方式实现:
user.invoices.where(hide: false).map do |invoice|
invoice.attributes.merge({
email_payment: invoice.payments.last.email,
created_at_payment: invoice.payments.last.created_at
})
end