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.