ruby-on-rails - 如何连接表以仅获取 has-many 关联的最后一条记录?

我有两个模型:公司和交易(有很多关系)。事务模型具有 balance 属性。我有一个加入模型的查询:

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

但是,我只想将最后一笔交易包含在此查询中。结果 Company.joined_transactions.first.current_balance == Company.first.transactions.last.balance 应该为真。

最佳答案

子查询 .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)')

https://stackoverflow.com/questions/35441135/

相关文章:

asp.net-mvc - ASP.net MVC : Identity and drop auth

angularjs - UI-Grid 分页模板可编辑

turing-machines - PCP 可以识别吗?

sql - Knex 原始查询不工作 postgresql

vim - tmux 将选择从复制模式发送到其他 Pane (xargs 加入?)

visual-studio - 如何在 Google Chrome 扩展程序中创建侧边栏?

amazon-web-services - 更新和部署 Elastic Beanstalk 应用程序

python - 使用 gensim 库进行内存高效 LDA 训练

oracle - 安装 Oracle ODAC 12c 第 4 版 (12.1.0.2.4) 时出现

html-table - 在单个表格行 中混合表格标题 和表格数据 单