将lambda表达式或某些参数添加到'has_one'关联中

时间:2013-01-18 04:02:00

标签: ruby-on-rails rails-activerecord

假设我的模型是这样的:

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

2 个答案:

答案 0 :(得分:0)

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

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

不确定如何将其限制为 last 租借。你的意思是按日期排的最后一个吗?

答案 1 :(得分:0)

您正在尝试创建一个子查询(用于最大日期),该子查询依赖于Movie实例的ID,当您查询整个Model类时,该ID在预备加载阶段不可用。所以,我认为不可能加载。

您可以使用已粘贴的查询创建自定义视图,并编写模型以访问视图。然后,您将为每部电影创建多个记录,每个客户的上次租赁日期,您只需要查询特定电影和客户的记录。