ruby on rails - Sort by specific ids in ActiveRecord -


i have inherited programmer's rails3 project, , i'm new rails overall. he's got query appears sort specific id's. can explain how resolves in actual sql? think code killing db , subsequently rails. i've tried output in logger can't seem actual sql output config set :debug. searching heavily here (on so) didn't turn clear explanation of how query looks. code looks like:

options = {               select: "sum(1) num_demos, product_id ",               group:  "product_id",                               order:  "num_demos asc",             }   product_ids = demo.where("state = 'waitlisted'").find(:all, options).collect{|d| d.product_id}   sort_product_ids = product_ids.collect{|product_id| "id = #{product_id}"}      product.where(visible: true, id: product_ids).order(sort_product_ids.join(', '))    

as far can see, final line create query against product table order "id = 1, id = 3, ..." etc, doesn't make lot of sense me. clues appreciated.

a quick breakdown of what's going on, it'll understand replacement query.

options = {               select: "sum(1) num_demos, product_id ",               group:  "product_id",                               order:  "num_demos asc",             } product_ids = demo.where("state = 'waitlisted'").find(:all, options).collect{|d| d.product_id} 

this line generate

select sum(1) num_demos, product_id "demos" (state = 'waitlisted') group product_id 

and returns array of demo objects, sorted count(*) of rows in group, product_id attribute has been loaded, , available you.

next,

sort_product_ids = product_ids.collect{|product_id| "id = #{product_id}"}    

results in collection of product_ids mapped format "id = x". ie: if previous result returned 10 results, product_ids ranging 1..10, sort_product_ids equivalent ["id = 1", "id = 2", "id = 3", "id = 4", "id = 5", "id = 6", "id = 7", "id = 8", "id = 9", "id = 10"]

finally,

product.where(visible: true, id: product_ids).order(sort_product_ids.join(', ')) 

selects products column visible true, , id in array of product_ids (which, found out earlier, array of demo objects, not integers - might causing query fail). then, asks sql sort result list sort_product_ids (sent in string "id = 1, id = 2, ... id = 10" instead of array ["id = 1", "id = 2", ... "id = 10"]).

more info available at: http://guides.rubyonrails.org/active_record_querying.html http://api.rubyonrails.org/classes/activerecord/querymethods.html


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

c++ - Clear the memory after returning a vector in a function -

erlang - Saving a digraph to mnesia is hindered because of its side-effects -