0

I have a form, where I have three input fields, the user can - well - use. Two are dropdowns, one for date, etc anotherone for tags. The last one is a search input, which is connected to elasticsearch in the backend.

Now I have the question to find a appropriate where clause to inhibit all circumstances i.e. all possible combinations. I could do something like in this answer, but in my case I assume that this will lead to messy code, which is why I am looking for a more elegant way. Tags and videos have a has_and_belongs_to_many-associations.

Here is what I have so far:

if params[:sort].blank? || params[:sort].nil?
  params[:sort] = sort_column + ' ' + sort_direction   
else
  if params[:sort] == "date"
    params[:sort] = "created_at"
  elsif ...
  end     
end

if params[:tag].blank? || params[:tag].nil?
  params[:tag] = "*"
end

if params[:q].blank? || params[:q].nil?
  params[:q] = "*"
end

And my query

@models = @Model.joins(:tags).where(tags: {name: params[:tag]}, videos: {event_id: params[:event_id]}).order(params[:sort]).page(params[:page]).search(params[:q]).records

What would be the most elegant solution? The one above does not work. For a url where only the tag is selected, it will return all elements.

Community
  • 1
  • 1
stiller_leser
  • 1,512
  • 1
  • 16
  • 39
  • Have you taken a look at a gem called `ransack`, it's often used for this kind of situation. – Eyeslandic Jun 26 '14 at 18:01
  • 3
    No need to use both .blank? and .nil?. .blank? covers nil values too. http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F – Nitish Parkar Jun 26 '14 at 18:04
  • The [has_scope](https://github.com/plataformatec/has_scope) gem would work well for this. – infused Jun 26 '14 at 19:54
  • Thanks for all your suggestions. I actually wrote done all possible combinations. Turned out, that I was overestimating them. I ended up with around ten cases, which is fine I guess. – stiller_leser Jun 26 '14 at 20:25

0 Answers0