BBB
BBB

Reputation: 85

Configuring rails database query so that blank string parameters are ignored

I'm making a rails application so that users can search a database of midi records and find midi files that correspond to the attributes that I've given them. For example, a user might enter data into an html form for a midi file with name = "blah" composer= "buh" and difficulty = "insane". This is all fine and well, except that I would like when the user enters no data for a field, that field is ignored when doing the select statement on the database. Right now this is what my select statement looks like:

@midis=Midi.where(:name => params[:midi][:name],
                  :style => params[:midi][:style],
                  :numparts => params[:midi][:numparts],
                  :composer=> params[:midi][:composer],
                  :difficulty => params[:midi[:difficulty])

This works as expected, but if for example he/she leaves :composer blank, the composer field should not considered at all. This is probably a simple syntax thing but i wasn't able to find any pages on it.

Thanks very much!

Upvotes: 0

Views: 201

Answers (2)

Harish Shetty
Harish Shetty

Reputation: 64363

Try this:

# Select the key/value pairs which are actually set and then convert the array back to Hash
c = Hash[{
    :name       => params[:midi][:name],
    :style      => params[:midi][:style],
    :numparts   => params[:midi][:numparts],
    :composer   => params[:midi][:composer],
    :difficulty => params[:midi][:difficulty]
  }.select{|k, v| v.present?}]

Midi.where(c)

Upvotes: 1

clemensp
clemensp

Reputation: 2510

Not sure if Arel supports that directly, but you could always do something like:

conditions = {
  :name => params[:midi][:name],
  :style => params[:midi][:style],
  :numparts => params[:midi][:numparts], 
  :composer=> params[:midi][:composer],
  :difficulty => params[:midi[:difficulty]
}

@midis=Midi.where(conditions.select{|k,v| v.present?})

Upvotes: 3

Related Questions