3

I have two models: Company and Transaction (has-many relationship). Transaction model has balance attribute. I have a query to join the models:

scope :joined_transactions, (lambda do
  select('transactions.balance as current_balance')
  .joins('LEFT OUTER JOIN transactions ON transactions.company_id = companies.id')
end)

However, I want to include only the last transaction into this query. As a result Company.joined_transactions.first.current_balance == Company.first.transactions.last.balance should be true.

yzalavin
  • 1,788
  • 1
  • 13
  • 19

2 Answers2

6

subquery .joins('left join transactions t on t.company_id = companies.id AND t.id = (SELECT MAX(id) FROM transactions WHERE transactions.company_id = t.company_id)')

haroldus
  • 111
  • 1
  • 3
-3

I believe this problem was already solved many times. You can do it using subquery or double join.

Please add more info on your current case if this doesn't work for you

Community
  • 1
  • 1
faron
  • 1,051
  • 7
  • 9