简体   繁体   中英

Rails query through multiple models

It's been 2 days by now that I'm struggling to write query. So, I'm trying to query within these 3 related models:

class Company...
  has_many :programs
end

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

class Transaction...
  belongs_to :program
end

As output, I need a list of the amount of all Transactions each Company made and on what date.

Your query should be something like this.

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

You could change the format of the date by referring to strftime method of Time class from here - http://ruby-doc.org/core-2.2.0/Time.html#method-i-strftime .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM