Rails 强制在 where 子句中执行 SQL 查询

Nis*_*mar 4 activerecord query-optimization ruby-on-rails-4

这是我的代码:

list_views = ListView.where(:user_id => current_user.id)
total_list_views = list_views.size
top_recommended_lists = recommendations_based_on_list_views(list_views, language_score_hash, level_score_hash, category_score_hash)
Run Code Online (Sandbox Code Playgroud)

然后就是这个方法

def recommendations_based_on_list_views(list_views, language_score_hash, level_score_hash, category_score_hash)
  viewed_lists_ids = list_views.map {|list_view| list_view.list_id}.uniq
  ....
Run Code Online (Sandbox Code Playgroud)

问题在于这段代码在ListView模型一上执行了 2 个查询list_views.size,然后在list_views.map {|list_view| list_view.list_id}.uniq

如果我们可以强制执行查询,那么只需要ListView.where(:user_id => current_user.id)对模型进行单个查询,或者如果有任何其他方式ListView

如何实现这一目标?

Nis*_*mar 5

找到了这个方法。我们可以用loadlist_views = ListView.where(:user_id => current_user.id).load

https://apidock.com/rails/ActiveRecord/Relation/load