ruby on rails - ActiveRecords: Search only on non empty parameters -
so have search on 3 fields. age , sex , ethnicity
if age given have return records matching age. if age , ethnicity given sex empty return matching records age , ethnicity. etc..
the naive way of solving this:
class profile def self.search_profile(search_params_array) if search_params_array.first != nil && search_params_array.second != null && search_params_array.third != null profile.where("age = ?", search_params_array.first).where("sex = ?", search_params_array.second).where("ethnicity = ?", search_params_array.third) end ... ... # can permutate between possible conditions 1 of element nil ... end end
what better way approach this?
class profile def self.search_profile(search_params_array) params = %w(age sex ethnicity).zip(search_params_array).reject |_, v| v.nil? end.to_h where(params) end end
if can pass search params hash, things can easier.
Comments
Post a Comment