0

假设我的模型是这样的:

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
4

2 回答 2

0

You are trying to create a subquery (for max date) which depends back on the Movie instance's ID, which is not available at the eager loading stage when you are querying upon the entire Model class. So, I don't think eager loading is possible.

You can create a custom view with the query you have pasted, and write a model to access the view. Then you will have multiple records for each movie with last rental date per customer and you just to have query on the record for a particular movie and customer.

于 2013-01-19T03:16:29.190 回答
0

假设您将Rentals模型重命名为Rental,这将急切地加载指定客户(在本例中为名为“brian”的用户)的所有租金:

Movie.includes(:rentals => :customer).where('customers.name = "brian"')

不过,不确定如何将其限制为最后一次出租。你是说最后一个日期吗?

于 2013-01-18T04:43:03.267 回答