Railed Database嵌套搜索混淆:第2部分

时间:2016-10-19 18:41:49

标签: mysql sql ruby-on-rails

前段时间我问this question

这是我的疑问:

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

但是,我现在有一个我要搜索的第二个嵌套属性 - 游戏!

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

但这不起作用。我究竟如何一起加入他们?

1 个答案:

答案 0 :(得分:1)

你错过了一个点。

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

写这个的更好方法是

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