Nitisha
Nitisha

Reputation: 101

Get single record from has_many using eager-loading in include

I'm new to rails and stuck between eager-loading from last 2 days. I have two models Car and Images with Car has_many :images association. and I have made an api which returns json array of cars with their images. I want single image instead all images from association. I'm using like:

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

This will return all the cars with their all images. I want all cars with their single image instead of all images array.

Upvotes: 0

Views: 488

Answers (2)

DjezzzL
DjezzzL

Reputation: 845

You should add has_one :image, -> { order(updated_at: :desc) } to Car model. This will define a default_scope to the association.

Then you could get all cars with only one last updated image per car:

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

Upvotes: 2

Kamil Puchała
Kamil Puchała

Reputation: 1

It's depend what you need.

  1. If You need first, please write: Car.where(company: "BMW").first
  2. If you need last, please write: Car.where(company: "BMW").last

Is it enough for you?

If you have has_many association you have to choose what record you need (maybe add some flag). Without that you will have collection from all association object.

One more is better to use where(company: "BMW") than where(:company => "BMW")

Upvotes: 0

Related Questions