假设我的模型是这样的:
class Movie
has_one :last_rental_from_a_specific_user, :class_name => 'Rentals'
has_many :rentals
end
class Rental
belongs_to :movie
belongs_to :customer
# date of the rental attribute
end
class Customer
has_many :rentals
end
如何找到所有电影并包括(急切加载,而不是延迟加载)指定客户最后一次租借的每部电影?
就像是:
@x = Movie.includes(:last_rental_from_a_specific_user("jsmith")).first
@x.last_rental_from_a_specific_user.date
它在 SQL 中看起来像这样:
select
*
from
movies left join
(select * from rentals where movie_id = movies.id and user_id = ? and rental_date =
(select max(rental_date) from rentals where movie_id = movies.id and user_id = ?))
as tmp on movies.id = tmp.movie_id