【发布时间】:2014-07-08 16:56:17
【问题描述】:
我有一个 Place 模型和一个 Event 模型。地点可以举办在特定日期发生的活动。
如何设置我的关联和查找器以加载所有地点,包括(急切加载)他们在特定日期的事件而不会出现 N+1 查询问题?
我尝试过的:
class Place
has_many :events
end
Place.all.preload(:events).where("events.start_date > '#{time_in_the_future}'")
#ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "events".
Place.all.includes(:events).where("events.start_date > '#{time_in_the_future}'").references(:event)
# only loads places that have an event at the specific date and not all places including their events (if there are any events).
我成功地想出了一个可以做我想做但不是动态的关联(不接受参数)
class Place
has_many :events, -> {where("events.start_date > '#{Time.now}'")}
end
Place.all.preload(:events)
# perfect: executes two queries: One to get all 'places' and one to get all 'events' that belong to the places and merges the 'events' into the 'place' objects.
# But I can't pass time as a parameter, so time is always Time.now (as specified in the has_many association).
# Place.all.preload(:events).where(xyz) gives wrong results like the examples above.
对我来说,问题是我找不到在动态条件下预加载/急切加载的方法。因为预加载和包含期望关联名称作为参数并且不能使用参数进行细化。至少我发现没有办法做到这一点。
【问题讨论】:
-
这是一篇很好的文章,解释了 Rails 中的预加载:blog.arkency.com/2013/12/rails4-preloading
-
谢谢,但已经读了几遍这篇文章,但是在预加载时找不到动态条件的信息。
-
也找不到将参数传递给 ActiveRecord::Associations::Preloader 的方法。覆盖或子类化似乎是一种错误的方法。
标签: ruby-on-rails ruby activerecord preloading