Rails, finder in the model (using collection) or in the controller (iterating and using push). Which is more efficient?

which below is more effective for this task. I want to loop through the model, check if the list consisting of the whole shafts associated with each model_id is greater than 0. If then we take the corresponding models into the list of models.

@models = Model.find(:all).collect{|m| m }.reject{ |i| modellist[i.id] < 1 } 

or how is it

 finalModels = [] Model.find_each do |model| if modellist[model.id] > 0 #edited #if modellist[model.id] != 0 finalModels.push( model ) end end @models = finalModels 

Im leaning towards the second approach, but not sure. Perhaps some insight into how .collect and .reject work in order to understand how effective it is.

  • Edit

My model is called Picture. modellist (or pList) contains data like this.

 [nil,nil,nil,3,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil, nil,nil,7,nil,nil,nil,0,nil,nil,nil,0,0,nil,nil,1,3] 

I pList index number corresponds to the image id for this. So I need to find pics where pList [image id] is greater than 0.

  • Edit

Used by Benoit Garrets. I needed to make sure that pList was declared pList = Hash.new, and not pList = []. the exact request i used was

 @pictures = Picture.find(pList.select {|k, v| v > 0}.keys) 
+4
source share
4 answers

Assuming your modellist and pList already exist and Hash , you can filter them before and use find with an array:

 @models = Model.find(modellist.reject {|k, v| v < 1} .keys) 

Same thing with the second example:

 @pictures = Picture.find(pList.reject {|k, v| v > 0} .keys) 

This way you won’t go through your entire database.

+2
source

You can simply do this in the database directly:

 @models = Model.find(:all, :conditions => ["id in (?)", modellist.select{ |i| i && i > 0}]) 

Or a shorter version:

 @models = Model.find(modellist.select{ |i| i && i > 0}) 
+6
source

Why not map the model array and display indexes / keys with values ​​not equal to 0, and pass this array of identifiers to the Finder of the model?

(some code will make noise, but I'm not in front of my computer)

+1
source

It is unreasonable to store values ​​in an array with an indexed identifier, because you cannot manipulate it without changing indexes and selecting all identifiers.

 ids = [] modellist.each_index{|i| ids << i if modelist[i] > 0} @models = Model.find ids 

If modellist was instead of a hash:

 @models = Model.find modellist.select{|k,v| v > 0}.keys 
+1
source

Source: https://habr.com/ru/post/1381488/


All Articles