如何查询 ActiveRecord 模型中的所有字段及其相关模型中的一个字段

How to query all fields from an ActiveRecord model AND one field from its related model

如果我有两个一对多的模型 foobar,我如何查询 foo 中的所有列然后查询 bar 中的单个列使用 Rails 查询界面?

换句话说,我如何将下面的查询翻译成 Rails:

select foo.*, bar.col from foo inner join bar on foo.bar_id = bar.id;

假设您有 Foo(with table foos) 和 Bar(with table bars) 作为 ActiveRecord 模型和 Foo 有很多 bars

你可以利用joins and select

可能是这样的:

Foo.joins(:bars).select("foos.*", "bars.col")