Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails force execution of SQL query in where clause

this is the code that i have:

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)

and then there is this method

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
  ....

problem is with this code 2 queries are executed on ListView model one at list_views.size and then at list_views.map {|list_view| list_view.list_id}.uniq

if we can force query execution at ListView.where(:user_id => current_user.id) then only single query to ListView model will be needed OR if any other way

how to achieve this ??

like image 314
Nishant Kumar Avatar asked Oct 27 '25 10:10

Nishant Kumar


1 Answers

Found the way to this. We can use load: list_views = ListView.where(:user_id => current_user.id).load

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

like image 53
Nishant Kumar Avatar answered Oct 30 '25 01:10

Nishant Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!