My model has a list of models. How do I load it from the database but limit the number of items in the list?

StackOverflow https://stackoverflow.com/questions/23530925

  •  17-07-2023
  •  | 
  •  

Question

In my Rails project I have a scenario where a car can have many parking tickets (I am using ActiveRecord). This is how I modelled it

class Car < ActiveRecord::Base
  has_many :parkingTickets, :order => "partkingTickets.date DESC"
end

class ParkingTickets < ActiveRecord::Base
    belongs_to :Car
end

And this is how I retrieve data:

@cars = Car.includes(:parkingTickets).order('ID, parkingTickets.date desc')

This works. But now I want to get the car only with the tickets from the last 12 months (if the ticket is older, I do not need it). Is there any way to express this using active record? I would not like to fetch a car and the fetch the parking tickets because this is a list of cars, so I would make many DB calls...

thanks!

Was it helpful?

Solution

A where condition should solve the issue:

@cars = Car.includes(:parkingTickets)
           .where('parkingTickets.date >= ?', 12.months.ago)
           .order('ID, parkingTickets.date desc')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top