I have a Company model that has_many balances and prices.
class Company < ActiveRecord::Base
has_many :balances, dependent: :destroy
has_many :prices, dependent: :destroy
end
The Balance and Price both have an date and amount columns.
I want to get recent 10 item of balances and same date of prices for them.
This is the code I wrote:
c = Company.first
balances = c.balances.order(:date).last(10)
prices = Balance.where(date: balances.map(&:date))
I think It is better that to join blances and prices table at first and select from the table by company_id and date.
But I couldn't figure out how to write it.
How can I write it?
I want to have a function like this in Rails way.
ActiveRecord::Base.connection.execute('SELECT "balances".*, prices.name FROM "balances" LEFT JOIN "prices" ON "balances"."date" = "prices"."date" where balances.company_id = 1 AND prices.company_id = 1 ORDER BY balances.date ASC').values.last(10)