Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
How to join multiple has_many relation table

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?

Edit

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)
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!