Guru on Rails

if you don’t sacrifice for your dream then your dream becomes your sacrifice.
Will Nguyen
Search Function with multiple filters
Fri 15 Jun 2018

Challenge: we need to build a function for searching including checkbox, plain text. 

Solution: 

  • Event: every time user clicks on a checkbox or pressing enter, any time the filters changed, an request will be sent to get results.
  • Processing data: checking parameters at server, checking hash key
    • in case they're null: excluding the where condition.
    • they have values: including the where condition.

Sometime console shows the error of FROM clause when we query the parents with conditions without adding parent's tables to FROM clause, we use joins:

def get_by_filters(collections, filters)
      where_clause = {}
      where_clause[:status] = filters[:statuses] unless filters[:statuses].nil?
      where_clause[:company_id] = filters[:companies] unless filters[:companies].nil?
      vessel_name = filters[:vessel_name]
      collections.where(where_clause).joins(:vessel).where("vessels.name ilike '?'", "%#{vessel_name}%")
end