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

℡╲_俬逩灬. 提交于 2020-01-03 05:34:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!