Rails通过多个模型查询
问题描述:
现在我已经2天了,我正在努力写查询。所以,我想这3个相关模型内查询:Rails通过多个模型查询
class Company...
has_many :programs
end
class Program...
belongs_to :company
has_many :transactions
end
class Transaction...
belongs_to :program
end
作为输出,我需要所有交易的每个公司制成,在什么时间量的列表。
答
您的查询应该是这样的。 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方法改变日期的格式。
请问您能否更好地解释您需要输出的内容? – Fallenhero
嘿@Fallenhero,我已经更新了这个问题。我现在明确自己还是不明白? –
那么@Fallenhero,我正在尝试'Transaction.joins(program :: company)',并用公司ID对它进行分组。但是,我不能无视这种方法。 :( –