A where
condition should solve the issue:
@cars = Car.includes(:parkingTickets)
.where('parkingTickets.date >= ?', 12.months.ago)
.order('ID, parkingTickets.date desc')
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!
Solution
A where
condition should solve the issue:
@cars = Car.includes(:parkingTickets)
.where('parkingTickets.date >= ?', 12.months.ago)
.order('ID, parkingTickets.date desc')