[英]Rails query through multiple models
到目前為止,我已經花了2天的時間來編寫查詢。 因此,我嘗試在以下3個相關模型中進行查詢:
class Company...
has_many :programs
end
class Program...
belongs_to :company
has_many :transactions
end
class Transaction...
belongs_to :program
end
作為輸出,我需要每個公司在什么日期進行的所有交易金額的列表。
您的查詢應該是這樣的。
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方法改變日期的格式http://ruby-doc.org/core-2.2.0/Time.html#method-i-strftime 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.