0

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!

2 Answers 2

3

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?})
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This solves my problem! I should have looked through the hash documentation first.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.