ineedahero ineedahero - 1 month ago 4
SQL Question

Railed Database Nested Search Confusion: part 2

A while back I asked this question.

This is my query:

def self.search(search)
query = "%#{search}%"
if search
joins(:hobbies)
.where("user_name like ? or first_name like ? or hobbies.name like ? or hobbies.type like ?", query, query, query, query)
else
self.all
end
end


However, I now have a SECOND nested attribute that I want to search by -- games!

def self.search(search)
query = "%#{search}%"
if search
joins(:hobbies)
joins(:games)
.where("user_name like ? or first_name like ? or hobbies.name like ? or hobbies.type like ? or games.number like ?", query, query, query, query, query)
else
self.all
end
end


But this doesn't work. How exactly do I join them all together?

Answer

You are missing a dot.

def self.search(search)
  query = "%#{search}%"
  if search
    joins(:hobbies)
    .joins(:games)
      .where("user_name like ? or first_name like ? or hobbies.name like ? or hobbies.type like ? or games.number like ?", query, query, query, query, query)
  else
    self.all
  end
end

The better way to write this is

def self.search(search)
  query = "%#{search}%"
  if search
    joins(:hobbies, :games)
      .where("user_name like ? or first_name like ? or hobbies.name like ? or hobbies.type like ? or games.number like ?", query, query, query, query, query)
  else
    self.all
  end
end