使用 include 中的预加载从 has_many 获取单条记录

Get single record from has_many using eager-loading in include

我是 rails 的新手,最近 2 天一直在急切加载。 我有两个模型 CarImagesCar has_many :images 关联。我制作了一个 api 其中 return 的 json 汽车阵列及其图像。我想要单个图像而不是来自关联的所有图像。 我正在使用:

Car.where(:company=>"BMW").as_json(:include=> {:images})

这将 return 所有汽车及其所有图像。 我希望所有汽车都具有单个图像而不是所有图像数组。

这取决于你需要什么。

  1. 如有需要请先写:Car.where(company: "BMW").first
  2. 如需最后请写:Car.where(company: "BMW").last

你够了吗?

如果你有 has_many 协会,你必须选择你需要的记录(也许添加一些标志)。如果没有它,您将拥有所有关联对象的集合。

使用 where(company: "BMW") 比使用 where(:company => "BMW")

更好

您应该将 has_one :image, -> { order(updated_at: :desc) } 添加到 Car 模型。这将为关联定义一个 default_scope

然后你可以得到每辆车只有一张最后更新图像的所有汽车:

Car.where(company: 'BMW').as_json(include: [:image])