2016-11-30 70 views
0

現在我已經2天了,我正在努力寫查詢。所以,我想這3個相關模型內查詢:Rails通過多個模型查詢

class Company... 
    has_many :programs 
end 

class Program... 
    belongs_to :company 
    has_many :transactions 
end 

class Transaction... 
    belongs_to :program 
end 

作爲輸出,我需要所有交易的每個公司製成,在什麼時間量的列表。

+0

請問您能否更好地解釋您需要輸出的內容? – Fallenhero

+0

嘿@Fallenhero,我已經更新了這個問題。我現在明確自己還是不明白? –

+0

那麼@Fallenhero,我正在嘗試'Transaction.joins(program :: company)',並用公司ID對它進行分組。但是,我不能無視這種方法。 :( –

回答

0

您的查詢應該是這樣的。 http://ruby-doc.org/core-2.2.0/Time.html#method-i-strftime -

Company.includes(:programs => :transactions).map do |company| {:company_name => company.name, :transactions => company.programs.map{|program| program.transactions.map{|t| {:amount => t.amount, :date => t.created_at.strftime("%d-%m-%Y")}}.flatten } end

你可以從這裏所指的時間類的strftime方法改變日期的格式。