我的模型的型号列表。如何从数据库中加载,但限制列表中的项目有多少? [英] My model has a list of models. How do I load it from the database but limit the number of items in the list?
问题描述
在我的Rails项目我有这样一个场景:一辆车可以有很多违规停车罚单(我用的ActiveRecord)。这是我仿照它
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')
这工作。 但现在我想要得到的车只能从过去12个月(如果票证是年纪大了,我并不需要它)的门票。 有什么办法能恩preSS这种使用活动记录?我不想去取车和获取停车票,因为这是汽车的名单,所以我会做很多数据库调用...
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...
谢谢!
推荐答案
A 其中,
情况应该解决的问题:
A where
condition should solve the issue:
@cars = Car.includes(:parkingTickets)
.where('parkingTickets.date >= ?', 12.months.ago)
.order('ID, parkingTickets.date desc')
这篇关于我的模型的型号列表。如何从数据库中加载,但限制列表中的项目有多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!