Search code examples
mysqlactiverecordassociations

ActiveRecord MySQL query "Like" from self and associations retrieves null if associations are non existant


I have the following scope:

 scope :scope_name_or_email_search, lambda { |query = ''|
    joins(:user_information)
      .where('
        users.email LIKE ? OR
        user_informations.first_name LIKE ? OR
        user_informations.last_name LIKE ?',
             "%#{query}%", "%#{query}%", "%#{query}%")
  }

This scope is retrieving only users with "user_informations" data.
If i search for "@" only the users with "user_informations" data are retrieved however all of them have the character "@" on their emails.

What would be the best approach?


Solution

  • The solution is quite simple. I need a join left on the query, so the ActiveRecord scope would become this:

    scope :scope_name_or_email_search, lambda { |query = ''|
        left_joins(:user_information)
          .where('
            users.email LIKE ? OR
            user_informations.first_name LIKE ? OR
            user_informations.last_name LIKE ?',
                 "%#{query}%", "%#{query}%", "%#{query}%")
      }