yzalavin
yzalavin

Reputation: 1836

How to join tables to get only the last record of has-many association?

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.

Upvotes: 3

Views: 4474

Answers (2)

haroldus
haroldus

Reputation: 131

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)')

Upvotes: 6

faron
faron

Reputation: 1059

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

Upvotes: -4

Related Questions