问题
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!
回答1:
A where condition should solve the issue:
@cars = Car.includes(:parkingTickets)
.where('parkingTickets.date >= ?', 12.months.ago)
.order('ID, parkingTickets.date desc')
来源:https://stackoverflow.com/questions/23530925/my-model-has-a-list-of-models-how-do-i-load-it-from-the-database-but-limit-the