2016-12-15 6 views
1

Ruby on Railsアプリケーションで別のオブジェクトにマージする必要があります。それらの間の多くの関係を1とRuby、2つの異なるオブジェクトをマージする

class Payment < ActiveRecord::Base { 
      :id => :integer, 
     :token => :string, 
    :invoice_id => :integer, 
    :created_at => :datetime, 
    :updated_at => :datetime, 
     :email => :string 
} 

class Invoice < ActiveRecord::Base { 
          :id => :integer, 
         :user_id => :integer, 
        :description => :text, 
          ...... 
         :status => :string, 
         :price => :float 
} 

そして、私の支払対象:私は私の請求書オブジェクトを持っている今、私がやりたいものを

class Invoice < ActiveRecord::Base 
    has_many :payments 

class Payment < ActiveRecord::Base 
    belongs_to :invoice 

返すことですInvoiceオブジェクトと、関連付けられた支払オブジェクトの:emailおよび:created_atフィールド。今、私はジップ機能を持つ2つのオブジェクトを返す:

: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}, 
    ... 
] 

どうやってやるの?

+1

は、あなたの 'Invoice'に' email_payment'と 'created_at_payment'メソッドを作成できませんでした。 'invoice'オブジェクトだけを使用しますか? – Magnuss

+0

はい、しかし論理的な観点からは、これはあまり意味がありません、私はより良い解決策があることを望みました! – ste

答えて

2

私は、請求書のモデルにメソッドとしてemail_paymentcreated_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 
+0

これは完璧です、まさに私が望んでいたものです! – ste

関連する問題