ruby on rails - ActiveRecord: Order by firstcolumn, (secondcolumn='foobar'), thirdcolumn...possible? -


i have activerecord query works follows:

a user searches zipcode - let's 90210. query identifies state (california), , returns results have match either in 'zipcode' field, or in 'state' field.

what i'd order results satisfy exact zipcode first. results precise zipcode '90210' ranked higher results satisfy 'california' state...keeping in mind results 90210 zipcode may have 'california' state.

any suggestions?

you don't dmbs use - in msysql can conditional order

:order => "if(zipcode = '#{params[:zipcode]}', 0, 1)" 

other dbms's might differently, think above standard though. alternative way

 :order => "(zipcode = '#{params[:zipcode]}') desc)" 

the desc necessary because if test implicit in above returns 1 true , 0 false, , 1 comes after 0 true results come after false results. hence desc shove true ones top.

i'm bit confused want though. if want find results state or zipcode matches params[:zipcode], push matching zipcode top,

yourmodel.find(:all,    :conditions => ["zipcode = ? or state = ?", params[:zipcode], params[:zipcode]],    :order => "if(zipcode = '#{params[:zipcode]}', 0, 1)") 

if want order other columns first (as suggested post title) put them before if call in order option, eg

:order => "name, if(zipcode = '#{params[:zipcode]}', 0, 1), zipcode" 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -