Optimal query in Ruby on Rails

时间:2015-05-24 20:59:33

标签: ruby-on-rails optimization active-record-query

I have to do an advanced search for a website (a kind of social network). In the view I have multiple inputs (the text typed in is taken in consideration when the search is performed). This is the query (I listed just two fields, but they are a lot more):

User.where("college like ?  or highschool like ?", "%#{params[:college]}%", "%#{params[:highschool]}%")

The problem appears when one of the inputs comes empty. Then the result will also contain users who didn't fill out the specific field and I don't want this (for example, if the input for college is empty when the form is submitted, then the results will contain users who didn't specify the college on their profile). One solution is to ask for every parameter if is empty or not and to make a query for every parameter not empty, but this seems not very optimal to me. Does anyone know a solution to this?

1 个答案:

答案 0 :(得分:1)

You might like to try Ransack, which will handle all this for you, and allow a range of predicates including LIKE and NOT LIKE.