stecd
stecd

Reputation: 1691

Query for only non-null Model attributes in ruby-on-rails

I am making an active record query for the Users that have matching attributes with the character parameter that gets passed into the suggestions(character) method. I want the like-attributes to get matched, and if a character's attribute is left blank, then it gets matched with any user.

How do I only query the attributes where the character.* (character.age, character.height, etc..) are NOT null?

For example, if one of my characters only has a name and age and its other attributes are left blank, therefore null, how do I not query them when calling User.where()? What other method on User could I use? side note: there are more attributes so it wouldn't make sense to separate each case into distinct methods.

  def suggestions(character)
    suggestions = User.where(
      age: character.age,
      height: character.height,
      weight: character.weight,
      gender: character.gender,
      ethnicity: character.ethnicity
    )
  end

Upvotes: 1

Views: 993

Answers (2)

neo-code
neo-code

Reputation: 1076

You need to remove the empty params out of your object and then perform the search :

def suggestions(character)
     character_params = character.attributes.dup
     search  = character_params.delete_if{|k,v| v.nil?}
     suggestions = User.where(search)       
end

Upvotes: 1

Achrome
Achrome

Reputation: 7821

You could very simply filter the character object to disregard nil values and then fire a query.

def suggestions character
  filter_character = {}
  character.serializable_hash.map {|key, value| filter_character[key] = value unless value.nil?}
  suggestions = User.where **filter_character
end

What this will do is serialize the original object, filter out nil values, then pass it back to the query as a splat.

This is a completely extensible approach and should work with any number of attributes on the object.

Upvotes: 2

Related Questions